Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Data Structures & Algorithms - Topic 5 - Array Data Structure

Uploaded by

arsalanbaig099
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Data Structures & Algorithms - Topic 5 - Array Data Structure

Uploaded by

arsalanbaig099
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

DATA STRUCTURES AND

ALGORITHMS

ARRAY DATA STRUCTURE

1
How Memory Works…???
■ You can imagine of memory as a chest
of drawers to store your things.

■ Each drawer can hold one element.

■ You want to store two things, so you


ask for two drawers.

2
How Memory Works…???
■ You store your two things here.

3
How Memory Works…???
■ This is basically how your
computer’s memory works.

■ Your computer looks like a


giant set of drawers, and each
drawer has an address.

■ Each address is some


hexadecimal number.
4
How Memory Works…???
■ Each time you want to store an
item in memory, you ask the
computer
for some space, and it gives you
an address where you can store
your
item.

■ If you want to store multiple


items, there are two basic ways to
do so: arrays and lists.
5
How Memory Works…???

■ Now you have understood how,


computer memory is organized.

■ You can think of memory as a


large tape of locations.

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)

Position Pascal Fortran C


Values Address
(P) Index (i) Index (i) Index (i)
A[i]
1 -3 1 0 50 1000 (A)

2 -2 2 1 25 1002

3 -1 3 2 40 1004

4 0 4 3 10 1006

5 1 5 4 35 1008

C Language: short int A[5] C Language: int A[0...4]


Fortran Language: int A[5] Fortran Language: int A[1...5]
Pascal Language: int A[-3...1] Pascal Language: int A[-3...1]
float A[5] = {50.50, 25.50, 40.50, 10.00, 35.00}
Array (Terminologies)
Values Address

Values Address
1000 4 address locations
50.50
4 bytes
50.50 1000
1004
25.50 25.50 1004

1008 40.50 1008


40.50 Word Size (W)
10.00 1012
1012 35.00 1016
10.00

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

Position Index Array A Address


Questions:
1 0 1000
What is the size of A? 9 2 1 1004
3 2 1008
What is the position of A[4]? 5
4 3 1012
What is the index of A8? 7 5 4 1016
6 5 1020
What is the address of A[4]? 1016 7 6 1024
8 7 1028
What is the address of A2? 1004
9 8 1032
Total memory occupied by A? 9*4 = 36B

Which element is on address 1028?A8 or A[7]


Array (Answer the Questions)
Data:Array A[-5...1] M = 2000 W = 2B

Position Index Array A Address


Questions:
1 -5 2000
What is the size of A? 7 2 -4 2002
3 -3 2004
What is the position of A[-4]?2
4 -2 2006
What is the index of A6? 0 5 -1 2008
6 0 2010
What is the address of A[-1]?2008 7 1 2012

What is the address of A8? Incorrect

What is the address of A[2]?Incorrect

Which element is on address 2004?A3 or A[-3]


Array (Answer the Questions)
Data:
Array A[-53...101] M = 1517 W = 4B
Questions:

What is the size of A? Wait a minute. I’m calculating on fingers.

What is the position of A[-4]? One second.

What is the index of A61? You’re confusing me.

What is the address of A[-1]? Stop it please.

What is the address of A[-54]? Incorrect.

Atleast, got 1 right answer.

Very difficult to answer because the array seems to be very big.


It is difficult to represent the array on paper.
Equations are needed to answer these questions.
Size = U – L + 1
Array (Formula to calculate Size)
Array A[0...4] Array A[1...5] Array A[-3...2]
L=0 L=1 L = -3
U=4 U=5 U=2

Index Index Index

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

Size(A) = U + 1 -0 Size(A) = U+ 1 -1 Size = 2 – (-3) + 1

Size(A) = U + 1 - L Size(A) = U + 1 - L Size = 2 + 3 + 1 = 6


Index =
Array (Formula to calculate Index from Position & vice-versa)
i = L + P - 1

Array A[0...4] Array A[1...5] Array A[-31...20]


L = 0, U = 4 L = 1, U = 5 L = -31, U = 20
Position Index Position Index Position Index
(P) (i) (P) (i) (P) (i)
1 0 1 1 1 -31
2 1 2 2 2 -30
3 2 3 3 3 -29
4 3 4 4 4 -28
5 4 5 5 Find index of 4th element.
Find index of element
Index(A1) = 0 Index(A1) = 1
located at position 4.
Index(A2) = 1= 2 - 1 Index(A2) = 2 Find index of A4.
Index(A3) = 2= 3 - 1 Index(A3) = 3
Index(Ap) = P - 1 Index(Ap) = P Index = i = L + P - 1
Index(Ap) = P – 1 +0 Index(Ap) = P-1 + 1 Index = i = -31 + 4 - 1
Index(Ap) = P – 1 + L Index(Ap) = P – 1 + L Index = i = -28
Address = M + ( i – L ) * W
Array (Formula to calculate Address from Index / Position)

Array A[0...4] Array A[1...5]


L = 0, U = 4, M=1000 L = 1, U = 5, M=1000
Index Address Index Address
(i) (i)
0 1000 1 1000
1 1001 2 1001
Will Word Size (W) matter?
2 1002 3 1002
Yes
3 1003 4 1003
4 1004 5 1004

Address(A[0]) = 1000 Address(A[1]) = 1000


Address(A[1]) = 1001= 1000 + 1 Address(A[2]) = 1001= 1000 + 1
Address(A[2]) = 1002= 1000 + 2 Address(A[3]) = 1002= 1000 + 2
Address(A[i]) = 1000 +=i M + i Address(A[i]) = 1000 + (i – 1)
Address(A[i]) = M + (i -0) Address(A[i]) = M + (i – 1)
Address(A[i]) = M + ( i – L )* W Address(A[i]) = M + ( i – L )* W
Address = M + ( i – L ) * W
Array (Formula to calculate Address from Index)

Array A[-5...1], L = -5, U = 1, M = 1000, W = 4

What is the address of element Index Address


located at index -1? (i)
What is the address of A[-1]? -5 1000
Address = M + (i - L) * W -4 1004
Address = 1000 + (-1 – (-5)) * 4 -3 1008

Address = 1000 + (-1 + 5) * 4 -2 1012


-1 1016
Address = 1000 + (4) * 4
0 1020
Address = 1000 + 16
1 1024
Address = 1016
Array
• Formulas / Equations:
– Size = U – L + 1
• U: Upper Bound of the array.
• L: Lower Bound of the array.
– Index or i = L + P – 1
• L: Lower Bound of the array.
• P: Position of element in the array.
– Address = M + (i – L) * W
• M: Base address of the array.
• i: Index of the element.
• L: Lower bound of the array.
• W: Word size of the array.
• Also called:
– Indexing Formula
• Could also be expressed in the form of Position ‘P’ as:
– Address = M + (P – 1) * W
» Because (i – L) = (P – 1)
Array (Indexing Formula)
Index Address
L Array in a Array in M
program memory
L+1 .
L+2 .
. .
. Address = M + (i – L) * W .
i .
. .
U-2 .
U-1 .
U .
Logical View Physical View
• Question-1:
– Suppose, an array A[-15...64] is stored in a memory whose
starting address is 459. Assume that the word size for each
element is 2. Then obtain the following:
• (a) How many number of elements are there in the array A?
• (b) How much memory is required to store the entire array?
• (c) What is the address location for A[50]?
• (d) What is the address location of 10th element?
• (e) Which element is located at address 599?
• Question-2:
– Suppose, an array A[-51...48] is stored in a memory whose
starting address is 1000. Assume that the word size for each
element is 4. Then obtain the following:
• (a) How many number of elements are there in the array A?
• (b) How much memory is required to store the entire array?
• (c) What is the address location for A[1]?
• (d) What is the address location of 53rd element?
• (e) Which element is located at address 1076?
Array
Index Array Question:
Increment all the values by 1.
A
Some Process/Procedure/Function
0 11 needs to be done on the array.

1 20 What is a ‘Process’ then?


2 9 ‘Process’ is a sequence of steps that is executed
to get the work done.
3 18 Example: Process of making Tea.
4 15 In Computer terminology, such process is called:
‘ALGORITHM’ / ‘PSEUDOCODE’.

Values When an Algorithm is implemented in a programming language,


it is called a:
(Marks of DSA
of 5 students) ‘PROGRAM’
Array Algorithm:TraverseArray
Travel through the array.
Visit each and every element of the array.

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

Will this algorithm work for any kind of array?


Question:
Whether C, Fortran, Pascal?
Whether Small array, Large array etc?
Will this algorithm be able to do any kind of processing?
Question:
i = -2
Iteration-1:

Array Condition: -2<=1 True


A[ -2 ] = 11 + 1 / Process(11)
Algorithm: TraverseArray i = -2 + 1 = -1
Iteration-2:
Trace the algorithm TraverseArray
Condition: -1<=1 True
on the following array.
A[ -1 ] = 20 + 1
i = -1 + 1 = 0
Iteration-3:
Index Array Steps:
Condition: 0<=1 True
A i=L
A[ 0 ] = 9 + 1
i L -2 11 While i <= U, do i=0+1=1
i -1 20 Iteration-4:
Process( A[ i ] )
i Condition: 1<=1 True
0 9 i=i+1
A[ 1 ] = 18 + 1
i U1 18
EndWhile i=1+1=2
Iteration-5:
i=2
Condition: 2<=1 False

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).

1 20 22 Search is unsuccessful.Return NULL.


2 9
Question:
Will TraverseArray algorithm be used here?
3 18

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

i = L, found = 0, location = NULL i = -1


, found =, 0location = NULL
While (i <= U) && (found == 0), doIteration-1:

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

Question:
Insert an element ’16’ in this array.
Question:
At which location / index, the element is to be inserted?

Index Array Index Array Index Array


A A A
0 11 0 11 0 11
1 20 1 20 1 20
2 9 2 2 9
3 18 3 18 3 18
4 15 4 15 4

Not possible. Possible.


Possible.
Last index /
Array is However, array seems location is
already full. to be polluted / corrupted. NULL.
Array Algorithm: InsertArray

Question:
Insert an element ’16’ in this array.
Question: 1
At which location / index, the element is to be inserted?

Index Array Solution-1: Index Array Solution-2:


A A
0 11 Steps: 0 11 Steps:
1 20
16 A[1] = 16 1 20
16 A[4] = A[1]
Stop A[1] = 16
2 9 2 9
Stop
3 18 3 18
4 4 20

Does not work. Does not work.


It should be insertion, not updation. Original sequence is changed,
hence polluted.
Array Algorithm: InsertArray

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?

Index Array Downward Shifting Index Array Downward Shifting


A starting from Top. A starting from Bottom.
0 11 0 11
Elements will be lost. All elements are preserved.
1 20 1 20
So it cannot work. So it can work.
2 9
20 2 9
20
3 18 3 9
18
4 4 18
Array Algorithm: InsertArray LOCATION
KEY
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

Index Array While (i > LOCATION) Controls the


A
A[ i ] = A [ i – 1 ] downward shifting
0 11 i=i–1 of elements.
1 20 EndWhile

2 9 A[LOCATION] = KEY
3 18 EndIf
Stop
4
KEY = 20, LOCATION = -1

Trace Algorithm: InsertArray -2 10


Index Array i=1
A -1 30
10 Steps: Iteration-1:
-2 40
Condition: 1 > -1 True 0
-1 30 If (A[U] != NULL), then A[ 1 ] = A[ 0 ] //A[1] = 40
1 40
print “Array is full. i=1–1=0
0 40 Insertion not possible.”
Else -2 10
1 50 Iteration-2:
i=U
Condition: 0 > -1 True -1 30
Index Array A[ 0 ] = A[ -1 ] //A[0] = 30
While (i > LOCATION) i = 0 – 1 = -1 0 30
A
A[ i ] = A [ i – 1 ]
-2 10 i=i–1 1 40
Iteration-3:
EndWhile
-1 30 Condition: -1 > -1False
-2 10
0 40 A[LOCATION] = KEY
EndIf 20
1 Stop A[ -1 ] = 20 -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 Empty location is in between the other elements of the array.


40
30 It should be at the tail end of the array.
3 40
50 So it leaves the array polluted / corrupted.

4 Can the last element ’50’ come to take place of


50
deleted element ’20’ directly?
No. Original sequence of elements will get changed.
Question: Will the It will pollute / corrupt the array.
upward shifting start
Hence the remaining values needs to shifted upwards
from Bottom / Top?
so that the empty space automatically moves downwards.
Array Algorithm:DeleteArray
Question:Delete an element from the array.
Question: 20
What is the value of the element to be deleted?

Index Array Index Array Solution-2:


A Solution-1: A
(Upward shifting
(Upward shifting
0 10 0 10 starting from Top)
starting from Bottom)
i = SearchArray(A, 20)
1 20 i = SearchArray(A, 20) 1 20
30

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

Question:Delete an element from the array.


Question: 20
What is the value of the element to be deleted?

While(i < 4), do


Index Array Steps:
A i = SearchArray(A, 20) i = SearchArray(A, 20) i = SearchArray(A, KEY)
// i = 1 // i = 1
0 10
While(i <= 3), do While(i < U), do
1 A[ 1 ] = A[ 2 ]
30
20
A[ 2 ] = A[ 3 ] A[ i ] = A[ i + 1 ] A[ i ] = A[ i + 1 ]
2 40
30 i=i+1 i=i+1
A[ 3 ] = A[ 4 ]
3 40
50 EndWhile EndWhile
4 50
A[ 4 ] = NULL A[ 4 ] = NULL A[ U ] = NULL
Index Array
A
0 60
Algorithm:DeleteArray
1 70 Question:
Delete an element with KEY = ’20’ from the array.
2 80
Steps:
3 90
i = SearchArray(A, KEY)
4 100 If( i == NULL ), then
print “KEY not found. Deletion not possible.”
Else
Index Array
A While(i < U), do
Controls the Upward Shifting
0 10 A[ i ] = A[ i + 1 ] of elements
1 i=i+1 starting from Top.
20
EndWhile
2 30
A[ U ] = NULL
3 40
EndIf
4 50 Stop
Trace Algorithm: DeleteArray
i = -1 11
Index Array KEY = ’22’ -2
A -1 == NULL False
Condition:
-1 33
-2 44 Steps:
Iteration-1: 0 33
-1 Condition:-1 < 1 True
55 i = SearchArray(A, KEY) 1 44
A[ -1 ] = A[ 0 ] //A[-1] = 33
0 66 If( i == NULL ), then
i = -1 + 1 = 0
print “KEY not found. -2 11
1 77
ElseDeletion not possible.”Iteration-2: -1 33
Condition:0 < 1 True
While(i < U), do 0 44
A[ 0 ] = A[ 1 ] //A[0] = 44
Index Array A[ i ] = A[ i + 1 ] 1 44
A i=0+1=1
i=i+1
-2 11 Iteration-3:
EndWhile Condition:1 < 1 False -2 11
-1 22
A[ U ] = NULL -1 33
A[1] = NULL
0 33 0 44
EndIf
1
1 44 Stop
Array
• Algorithm:
– DeleteArray.
• Input:
– Array A with elements.
– KEY: Element to be deleted.
• Output:
– On Success, Element with value KEY deleted from the array.
– On Failure, appropriate message to be displayed.
• Data Structure:
– Array A[L...U]
Two-Dimensional Array
■ The arrays we have discussed so
far are known as one-dimensional
arrays because the data are
organized linearly in only one
direction.
■ Many applications require that
data be stored in more than one
dimension.
■ One common example is a table,
which is an array that consists of
rows and columns. 54
Two-Dimensional Array (An Array of Arrays)

55
Two-Dimensional Array

■ This representation is called the array-of-arrays


representation.
■ Requires i contiguous memory of size k.
■ k is the number of columns in each row.
■ Suppose a 2D Array with 2 rows and 5 columns.
– Its logical and Physical view are shown below.

56
Question 3:
Calculate the Address of Elements of the following 2D Array

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 (suppose base address is 5000)
W = Storage Size of one element stored in the array (in bytes) – suppose
datatype of array is int
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

■ Multidimensional arrays
can have three, four, or
more dimensions.

■ The first dimension is


called a plane, which
consists of rows and
columns.

58
Multi-Dimensional Array

■ The C language
considers the three-
dimensional array to
be an array of two-
dimensional arrays.

■ The same concept


can be extended to
4D arrays and above.
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

The array is full


and there is no
room for a new
item!

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

The old array


will eventually
be deleted

71
Dynamic Arrays
■ Before every insertion, check to see if
the array needs to grow.

■ Question: When growing array, how


much to grow it?
– Memory efficient? (1, x2, etc.)
– Time efficient? (Create, Copy, Insert,
Delete)

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.

■ Therefore if we know the address of the first element


in the array and the size of each element we can
easily calculate the address of any element of the
array in the main memory.

76
Ungraded Assignment
■ Do proper calculations about Time Complexity and
complete the following table.

Operation on Static Dynamic


Array Array Array
Update O(1) O(1)
Traverse
Search
Insertion
Append
Deletion

77
Ungraded Assignment

■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.

78
End of Lecture

THANK YOU
79

You might also like