Data Structures: Hapter
Data Structures: Hapter
Chapter 04
9/9/2024 Md. Golam Moazzam, Dept. of CSE, JU 1
Data Structures- Chapter 4
❑ Linear Array
– Let the array name be A. Then the elements of A are: a1, a2, ….., an.
– Or by the bracket notation: A[1], A[2], A[3],…………., A[n]
– The number k in A[k] is called a subscript and A[k] is called a
subscripted variable.
9/9/2024 Md. Golam Moazzam, Dept. of CSE, JU 3
Data Structures- Chapter 4
❑ Linear Array
Example:
– A linear array DATA consisting of six elements:
DATA
1 247 DATA [1] = 247
2 56 DATA [2] = 56
3 429 DATA [3] = 429
4 135 DATA [4] = 135
5 87 DATA [5] = 87
6 156 DATA [6] = 156
– LB = 1932, UB = 1984
Solution:
(a) The number of elements is equal to the length; hence use the formula
Length = UB –LB+1
Accordingly, Length(AAA) = 50-5+1=46
Length(BBB) =10-(-5)+1=16
Length(CCC) = 18-1+1=18
Solution:
(b) Use the formula, LOC(AAA[K]) = Base(AAA) + w(K –LB)
Hence, LOC (AAA[15])=300+4(15-5)=340
LOC(AAA[35])=300+4(35-5)=420
AAA[55] is not an element of AAA, since 55 exceeds UB=50
Pass 1: (a) Compare A1 and A2. Since 32< 51, the list is not altered.
A: 32, 51, 27, 85, 66, 23, 13, 57
(b) Compare A2 and A3. Since 51>27, interchange 51 and 27.
A: 32, 27, 51, 85, 66, 23, 13, 57
(c) Compare A3 and A4. Since 51<85, the list is not altered.
A: 32, 27, 51, 85, 66, 23, 13, 57
(d) Compare A4 and A5. Since 85>66, interchange 85 and 66.
A: 32, 27, 51, 66, 85, 23, 13, 57
Pass 1: (e) Compare A5 and A6. Since 85>23, interchange 85 and 23.
A: 32, 27, 51, 66, 23, 85, 13, 57
(f) Compare A6 and A7. Since 85>13, interchange 85and 13.
A: 32, 27, 51, 66, 23, 13, 85, 57
(g) Compare A7and A8. Since 85>57, interchange 85 and 57.
A: 32, 27, 51, 66, 23, 13, 57, 85
Pass 1: P E O P L E, E P O P L E, EOPPLE
E O P P L E, E O P L P E, EOPLEP
Pass 2: E O P L E P, E O P L E P, EOPLEP
E O L P E P, EOLEPP
Pass 3: E O L E P P, E O L E P P, ELOEPP
ELEOPP
Pass 4: E L E O P P, E L E O P P, EELOPP
Pass 5: E E L O P P, EELOPP
Algorithm 4.6: (Binary Search) BINARY (DATA, LB, UB, ITEM, LOC)
Here DATA is a sorted array with lower bound LB and upper bound UB,
and ITEM is a given item of information. The variables BEG, END and
MID denote respectively the beginning, end and middle locations of a
segment of elements of DATA.
Example:
– If a given sorted array contains 1024 elements, then the maximum
number of comparisons required is:
log2(1024) = 10 (only 10 comparisons are enough)