Data Structures Algorithms - Lecture 15 16 17 - Array Data Structure
Data Structures Algorithms - Lecture 15 16 17 - Array Data Structure
AHMED
2
How Memory Works…???
■ You store your two things here.
3
How Memory Works…???
■ This is basically how your computer’s
memory works.
5
How Memory Works…???
6
How Memory Works…???
■ Any location on this tape can be randomly accessed by its address.
7
Variable
– Placeholder/Structure to store a basic unit of data.
– Example:
• 1 integer variable stores single integer data.
• 1 float variable stores single float data.
– Question is:
• In a computer, where is that value assigned to a variable stored?
– In memory, possibly Random Access Memory (RAM)
• But where exactly in memory?
– On some physical address in memory because,
» Memory is divided in physical locations and,
» Each location has a particular address associated with it.
Variable
1000
5
(a)
int a = 5;
1001
char n = ‘z’; 1002
1003
1004
1005
1006
1007
1008
z (n)
1009
Array
• Need:
– Sometimes in our program,
• There might be a need to store multiple data of similar type.
– Example:
• Roll numbers of 10 students.
• Marks of DSA of 10 students.
– 2 solutions:
• Create different variables each having a different name.
– int num1, num2, num3 etc.
• Create a collection of variables referred by a common name.
– int num[3]
– This looks much better solution.
Array
1000 (a)
short int a = 5;
5 1001
char n = ‘z’; 1002
B 1003 (name)
char name[3] = {‘B’, ‘o’, ‘b’};
o 1004 Ordered
b 1005
Finite
1006
1007
Same data type
/
1008
z (n)
Homogeneous 1009
Array
• Array:
– Finite, Ordered collection of Homogeneous data elements where,
• Ordering is maintained by storing all elements in,
• Continuous / Contiguous locations of memory.
– Properties:
• Finite:
– Contains only a limited (finite) number of elements.
• Ordered:
– All elements are stored one by one in continuous / contiguous locations of computer memory.
• Homogeneous:
– All the elements of an array are of the same data type.
– Example:
• An array of integers to store the roll numbers of all students in a class.
• An array of strings to store the names of all villagers in a village.
Array (Terminologies) Size / Length / Dimension
Lower Bound (L) short int A[5] = {50, 25, 40, 10, 35} Base Address (M)
Upper Bound (U)
2 -2 2 1 25 1002
3 -1 3 2 40 1004
4 0 4 3 10 1006
5 1 5 4 35 1008
Values Address
1000 4 address locations
50.50
4 bytes
50.50 1000
1004
25.50 25.50 1004
1016
35.00
Array
• Terminology:
– Size:
• Number of elements in an array.
• Also called:
– Length, Dimension.
• Example:
– int A[5]
» Size is 5.
– Type:
• Kind of data type it is meant for.
• Example:
– int A[5]
» Type is int.
– Base / Base Address (M):
• Address of the memory location where the first element of the array is located.
• Denoted by symbol M.
Array
• Terminology:
– Index (i):
• Subscript by which the elements in an array can be referenced / accessed.
• Always an integer value.
• Lower Bound (L):
– Starting index of an array.
– Denoted by symbol L.
• Upper Bound (U):
– Ending index of an array.
– Denoted by symbol U.
• Example:
– A[1]: Element located on index 1.
– A[-3]: Element located at index -3.
Array
• Terminology:
– Range of Indices:
• Depends on the programming language in which the array is created.
– In C,
» Index always starts from 0 upto Size-1.
– In Fortran,
» Index always starts from 1 to Size.
– In Pascal,
» Index can have user-defined integer values.
– Position (P):
• Relative rank of an element in the array.
• Does not depend on the programming language.
• Example:
– A1:First element in the array.
– A5:Fifth element in the array.
– Word Size (W):
• Size of one element in the array.
• Denoted by symbol W.
Array (Answer the Questions)
Data: Array A[0...8] M = 1000 W = 4B
0 L 1 -3
1 2 -2
2 3 -1
3 4 0
4 U 5 1
2
Size(A) = 5 Size(A) = 5
Size(A) = U + 1 Size(A) = U Size = U – L + 1
Index Array
A Steps:
0 11 i=0
A[0] = A[0] + 1 For i = 0 to 4
While i <= 4, do
1 20 A[1] = A[1] + 1
A[ i ] = A[ i ] + 1 A[ i ] = A[ i ] + 1
2 9 A[2] = A[2] + 1
i=i+1
A[3] = A[3] + 1
3 18
A[4] = A[4] + 1 EndWhile EndFor
4 15
Same thing is being done
repetitively just using
different values.
Better to do it using a Loop.
TRACING
Array i=0
Algorithm: TraverseArray
Iteration-1: Condition 0 <= 4 True
Question: Increment all the values by 1. A[0] = 11+1 = 12
i=0+1=1
Index Array Steps: Iteration-2: Condition 1 <= 4 True
A A[1] = 20+1 = 21
0 11 i=0 i=1+1=2
1 20 While i <= 4, do Iteration-3: Condition 2 <= 4 True
A[ i ] = A[ i ] + 1 A[2] = 9+1 = 10
2 9 i=2+1=3
3 18 i=i+1 Iteration-4: Condition 3 <= 4 True
A[3] = 18+1 = 19
4 15 EndWhile i=3+1=4
Check whether this algorithm Iteration-5: Condition 4 <= 4 True
is working for this array or not. A[4] = 15+1 = 16
i=4+1=5
How to check whether an algorithm
is working or not? Iteration-6: Condition 5 <= 4 False
Array
Algorithm: TraverseArray
Steps:
Index Index Array
A i=0 i=L
-2 0 11
While i <= 4, do While i <= U, do
-1 1 20
A[ i ] = A[ i ] + 1 A[ i ] = A[ i ] + 1
0 2 9 i=i+1 i=i+1
1 3 18
EndWhile EndWhile
2 4 15
Stop
Array
• Algorithm:
– TraverseArray.
• Input:
– Array A with elements.
• Output:
– According to Process().
• Data Structure:
– Array A[L...U]
Array
Algorithm: TraverseArray
Steps:
i=L
While i <= U, do
Process( A[ i ] )
i=i+1
End While
Stop
Array Algorithm: SearchArray
Index Array
A
0 11 9 Search is successful. Return 2 (Index of 9).
4 15
Algorithm: SearchArray
i=L (i <= U)
Steps:
KEY = 9
i = 0 , found = 0 , location = NULL
While (i <= 4) && (found == 0), do
Index Array If (A[ i ] == KEY)
A Process
If( A[ i(A[
] ==i ])
9 ), then
Question:
0 11 found = 1
Is it the most optimized / efficient?
1 20 location = i
EndIf Question:
2 9
Will it work for any array?
i=i+1
3 18
EndWhile Question:
4 15 Will it work for any search value?
If (found == 0), then
print “Search is unsuccessful.”
Else
print “Search is successful.”
EndIf
Return(location)
Trace Algorithm: SearchArray
Steps: KEY = 20
Index Array If( A[ i ] == KEY ), then Condition: -1<=2 && 0==0 True
A If (11 == 20) False
found = 1
-1 11 location = i i = -1 + 1 = 0
0 20 EndIf Iteration-2:
Condition: 0<=2 && 0==0 True
1 9 i=i+1
If (20 == 20) True
2 18 EndWhile
found = 1
If (found == 0), then
location = 0
print “Search is unsuccessful.”
i=0+1=1
Else
Iteration-3:
print “Search is successful.”
Condition: 1<=2 && 1==0 False
EndIf
Search is successful
Return(location) Return (0)
Array
• Algorithm:
– SearchArray.
• Input:
– Array A with elements.
– KEY: Element to be searched.
• Output:
– On Success, appropriate message and return Index/Location of KEY in array A.
– On Failure, appropriate message and return NULL.
• Data Structure:
– Array A[L...U]
Array Algorithm: InsertArray
Index Array
A
0 11 It seems that the only solution is:
Shifting down of elements to make place for the new element.
1 20
2 20
9 Question: Will downward shifting start from Top or Bottom?
i.e. Will 20 be shifted down first or 18 will be shifted down first?
3 9
18
4 18
Array Algorithm: InsertArray
While (i > 1)
Index Array Steps:
A i=4 i=U
A[4] = A[3]
0 11 While (i >= 2) While (i > LOCATION)
1 16
20 A[3] = A[2] A[ i ] = A[ i – 1] A[ i ] = A[ i – 1]
i=i–1 i=i–1
2 20
9 A[2] = A[1]
EndWhile EndWhile
3 18
9
4 18 A[1] = 16 A[1] = 16 A[LOCATION] = KEY
Index Array
A Algorithm: InsertArray
0 11 Question: Insert KEY = ’16’ in this array at LOCATION = ‘1’.
1 20 Steps:
2 9
If (A[U] != NULL), then
3 18 print “Array is full. Insertion not possible.”
4 15 Else
i=U
2 9 A[LOCATION] = KEY
3 18 EndIf
Stop
4
KEY = 20, LOCATION = -1
0 30
1 40
Array
• Algorithm:
– InsertArray.
• Input:
– Array A with elements.
– KEY: Element to be inserted.
– LOCATION: Index where KEY is to be inserted.
• Output:
– On Success, Element with value KEY inserted at index LOCATION.
– On Failure, appropriate message to be displayed.
• Data Structure:
– Array A[L...U]
Array Algorithm: DeleteArray
Question: Delete an element from the array.
Question: What is the value of the element to be deleted?
Index Array
A
60 Element is not there in the array. It cannot be deleted.
0 10 20 Search is successful. 20 is available at index/location 1.
1 30
20 A[1] = NULL
2 30 2 40
30
An element is lost. All elements are
3 So this cannot work. 3 preserved.
40
50 40
50
So this can work.
4 50 4 50
Array Algorithm: DeleteArray
KEY
54
Two-Dimensional Array (An Array of Arrays)
55
Two-Dimensional Array
56
Calculate the Address of Elements
The address of elements w.r.t row and column number can be calculated
by the following formula:
Address of A [ I ][ J ] = B + W * [ C * ( I – Lr ) + ( J – Lc ) ]
Where,
B = Base address
W = Storage Size of one element stored in the array (in bytes)
Lr = Lower limit of row/start row index of matrix
Lc = Lower limit of column/start column index of matrix
C = Number of columns of the given matrix
57
Multi-Dimensional Array
58
Multi-Dimensional Array
59
Applications of Arrays
■ Arrays are used to implement mathematical vectors and matrices, as well
as other kinds of rectangular tables.
■ Many databases, small and large, consist of one-dimensional arrays
whose elements are records.
■ Arrays are used to implement other data structures, such as:
– Lists
– Heaps
– Hash tables
– Queues
– Stacks
– Etc. 60
Pros & Cons of Arrays
■ Good things:
– Fast, random access of elements.
– Very memory efficient, very little memory is required other than that needed
to store the contents.
■ Bad things:
– Slow deletion and insertion of elements.
– Size must be known when the array is created and is fixed (static).
61
Dynamic Data Structures
62
Dynamic Data Structures
63
Dynamic Arrays
■ Dynamic arrays are arrays that grow (or shrink)
as required
■ In fact a new array is created when the old array
becomes full by creating a new array object,
copying over the values from the old array and
then assigning the new array to the existing array
reference variable.
■ There is usually no limit on the size of such
structures, other than the size of main memory.
64
Dynamic Arrays
65
Dynamic Arrays
66
Dynamic Arrays
67
Dynamic Arrays
So we will create a
new, bigger array …
68
Dynamic Arrays
69
Dynamic Arrays
70
Dynamic Arrays
71
Dynamic Arrays
■ Before every insertion, check to see if the array
needs to grow.
72
Dynamic Arrays
■ Before every insertion, check to see if the array
needs to grow
■ Growing by doubling works well in practice,
because it grows very large very quickly
– 10, 20, 40, 80, 160, 320, 640, 1280, …
– Very few array re-sizings must be done.
– To insert n items you need to do log(n) re-sizings
■ While the copying operation is expensive it does
not have to be done often.
73
Dynamic Arrays
■ When the doubling does happen it may be time-consuming.
■ And, right after a doubling half the array is empty.
■ Re-sizing at each insertion would be prohibitively slow.
■ Similarly, we can have a blank array initially. As we add an
element, we can increase the size by 1. Same may be
considered for deletion; we decrease the size by 1 at each
deletion.
■ Time vs. Space Trade-off.
74
Summary
■ Static Array
– Advantages
■ Fast random access of elements (takes constant to access an element).
■ Efficient in terms of memory usage (almost no memory overhead)
– Disadvantages
■ Has a fixed size
■ Data must be shifted during insertions and deletions
■ Dynamic Array
– Advantages
■ Fast random access of elements.
■ Efficient in terms of memory usage (in terms of memory overhead)
– Disadvantages
■ Data must be shifted during insertions and deletions
■ Array may contain extra unused but reserved slots.
75
Why random access is fast in Array?
■ The elements in an array are stored at consecutive locations in the
main memory.
76
Assignment #3
■ Do proper calculations about Time Complexity and complete the
following table.
77
Assignment #3
■ Instructions:
– Consider only 1D arrays.
– Worst Case time complexity is required in each case.
– For Dynamic Arrays, consider increasing the size by 1 at each insertion.
Similarly, decreasing the size by 1 at each deletion.
■ .pdf file to be uploaded on LMS.
■ Deadline: Sunday, 20 September, 2020; before 23:55 HRS
■ Groups are NOT allowed.
■ Students having enrollment issues may email me the assignment at:
[email protected]
78
End of Lecture
THANK YOU
79