Data Structures & Algorithms: Lecture # 2 Dated: 28-10-2010
Data Structures & Algorithms: Lecture # 2 Dated: 28-10-2010
Lecture # 2
Dated: 28-10-2010
Example 2. formal Algorithm
representation
K 1
LOC 1
MAX DATA[1]
.
K K+1
Yes
Is K > N ? write: LOC, MAX
No
STOP
No
Is MAX< DATA[K]
Yes
LOC K
MAX DATA[K]
Today Topics
What are Arrays?
Memory
Address 101 103 105 107 109 111 113 115 117 119
0 1 2 3 4 5 6 7 8 9
LB UB
Index
Number
Memory representation of One
Dimensional Array
Maximum number of elements in a One-Dimensional
Array is computed as under:
Maximum number of elements = UB – LB + 1
UB – Upper Bound LB – Lower Bound
In pervious diagram UB = 9 and LB = 0
So, Maximum number of elements = 9 – 0 +1 = 10
L0 = 101, C = 2, k = 5
L(X(k)) = L0 + C * (k – 1)
L(X(5)) = 101 + 2 * (5 – 0)
= 101 + 2 * 4 = 101 + 10 = 111
Operations on 1-D Array
Traversal: Processing each element in the array
1 2 3 4
A[2,1]
1 12 1 -9 23 A[2,2]
Rows
2 14 7 11 121 A[2,3]
A[3,1]
A[3,4]
3 6 78 15 34
A[3,2]
Two Dimensional Array
Maximum number of elements in a Two-Dimensional
Array is computed as under:
Maximum number of elements = M x N
M – Number of rows N – Number of columns
In pervious diagram M = 3 and N = 4
So, Maximum number of elements =3 x 4 = 12
Values 12 1 -9 23 14 7 11 121 6 78 15 34
Memory 502 504 506 508 510 512 514 516 518 520 522 524
Address
Column-major order
1st Col 2nd Col 3rd Col 4th Col
Values 12 14 6 1 7 78 -9 11 15 23 121 34
Memory 502 504 506 508 510 512 514 516 518 520 522 524
Address
Note: Each integer occupies two bytes.
Row-Major Order
The memory address of an element with index i (row) and
j (Col) is computed as:
L(X[i][j]) = L0 + [(i – 1) * N + (j – 1)] * d
L0 = 502, d = 2, i = 2, j = 2, N = 4
L(X[i][j]) = L0 + [(i – 1) * N + (j – 1)] * d
L(X[2][2]) = 502 + [(2 – 1) * 4 + (2 – 1)] * 2
= 502 + [4 + 1] * 2 = 502 + 5 * 2 = 502 + 10 = 512
Col-Major Order
The memory address of an element with index i (row) and
j (Col) is computed as:
L(X[i][j]) = L0 + [(i – 1) + (j – 1) * M] * d
L0 = 502, d = 2, i = 2, j = 2, M = 3
L(X[i][j]) = L0 + [(i – 1) + (j – 1) * M] * d
L(X[2][2]) = 502 + [(2 – 1) + (2 – 1) * 3] * 2
= 502 + [1 + 3] * 2 = 502 + 4 * 2 = 502 + 8 = 510
Operations on 2-D Array
Traversal: Processing each element in the array
2 8 3 2 3 9
0 6 8 6 1 8
4 7 1 6 6 5
1 5 4 5 4 0
Representation of Stacks
Operations on Stacks
Push
Pop
Evaluation of Expressions