Data Structures & Algorithms - Topic 5 - Array Data Structure
Data Structures & Algorithms - Topic 5 - Array Data Structure
ALGORITHMS
1
How Memory Works…???
■ You can imagine of memory as a chest
of drawers to store your things.
2
How Memory Works…???
■ You store your two things here.
3
How Memory Works…???
■ This is basically how your
computer’s 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 (n)
z
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
short int A[5] = {50, 25, 40, 10, 35} Base Address (M)
Upper Bound (U)Lower Bound (L)
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
Question:
Increment all the values by 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
Question:
Search for an element and tell
whether it is present in the array or not.
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 =, 0location = NULL
While (i <= 4) && (found == 0), do
Index Array If (A[ i ] == KEY)
A Process
If( A[ i ] (A[
== i9])), 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
Question:
Insert an element ’16’ in this array.
Question:
At which location / index, the element is to be inserted?
Question:
Insert an element ’16’ in this array.
Question: 1
At which location / index, the element is to be inserted?
Question:
Insert an element ’16’ in this array.
Question: 1
At which location / index, the element is to be inserted?
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
Question:
Insert an element ’16’ in this array.
Question: 1
At which location / index, the element is to be inserted?
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
55
Two-Dimensional Array
56
Question 3:
Calculate the Address of Elements of the following 2D Array
57
Multi-Dimensional Array
■ Multidimensional arrays
can have three, four, or
more dimensions.
58
Multi-Dimensional Array
■ The C language
considers the three-
dimensional array to
be an array of two-
dimensional 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
… copy the
elements of the
old array into it
…
69
Dynamic Arrays
… and finally
insert 3 into
the new array.
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 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
Ungraded Assignment
■ Do proper calculations about Time Complexity and
complete the following table.
77
Ungraded Assignment
■Instructions:
78
End of Lecture
THANK YOU
79