You are on page 1of 19

Arrays

Chapter 2
Linear Array
• List of finite number of homogeneous data elements such-
• Elements referenced by index set( of consecutive numbers)
• Stored in successive locations.
• Length =UB – LB + 1
Representation in Memory
• Base(LA) = base or address of 1st element
• No need to save all locations 1000

1001

• LOC(LA[K]) = address of LA[K] 1002

= Base(LA) + w(K – LB) 1003

W= no of words per memory cell


Traversing
• Repeat for K=LB to UB:
• Process on LA[K]
• End
• Try for printing year and record of that year from 1932 to 1984
Insert & delete
• 2 locations:
• End of the array
• Middle of the array
• Insert: move latter elements downward
• Delete: move latter elements upward
Insert(LA,N,K,ITEM)
1. J=N
2. While J>=K:
1. LA[J+1] = LA[J]
2. J=J-1
3. LA[K]=ITEM
DELETE(LA,N,K,ITEM)
1. ITEM=LA[K]
2. For J=K to N-1:
1. LA[J] = LA[J+1]
2. J=J+1
3. N=N-1
Searching
• Linear Search
• Binary Search
Linear Search(DATA,ITEM,N)
1. DATA[N+1] = ITEM
2. LOC=1
3. While DATA[LOC] ≠ ITEM:
1. LOC = LOC + 1
4. IF LOC == N+1 :
LOC = 0
Complexity
Time Complexity:
• Best-case : O(1)
• Worst-case :O(n)
• Average case:O()

Space Complexity: O(1)


Binary Search(DATA,LB,UB,ITEM,LOC)
1. BEG=LB,END=UB, MID=)
2. While BEG ≤ END AND DATA[MID] ≠ ITEM:
1. If ITEM< DATA[MID]:
END = MID – 1
Else :
BEG = MID + 1
2. MID=)
3. If DATA[MID] == ITEM :
LOC = MID
Else:
LOC = 0
Complexity
• Time: O(
• Space: O(1)

Limitations
• Dataset needs to be sorted
• Need direct access to middle element
Multidimensional Array
• 2-dimensional array define size m x n.
• Each element specified by a pair of integers (i.e. I & J) such
1≤I ≤m and 1 ≤ J ≤n
• Element of array A : A[I,J] or AI,J
Representation in Memory
2-D array A can be store in memory in 2 ways:

• Column-major : column by column


• Row-major : row by row
Column-major order:
LOC[A[J,K] =Base(A) +w[M(K-1) + (J-1)]

Row-major order:
LOC[A[J,K] =Base(A) +w[N(J-1) + (K-1)]

Here. LB =1
Size of A =M x N
Pointer , Pointer Array
• Variable P is pointer if points to a certain element (contains location
of the element)
• Array Ptr is pointer array if each element points to a certain element
i.e. each one is pointer
• “Vectors” and “matrices” are mathematical terms are analogous,
respectively, to linear and two-dimensional arrays.
• An n-element vector V is a list of n numbers usually given in the form
V= (V1, V2, V3)
• An m X n matrix A is an array of m * n numbers arranged in m rows
and n columns
Matrix Multiplication
MATMUL(A, B, C, M, P, N)
Let A be an M x P matrix array, and let B be a P x N matrix array.
Product of A and B is an M x N matrix as array C

ALGORITHM:
1. Repeat for T=l toM:
Repeat for J = 1 to N:
1.Set C(I, J] := 0
2.Repeat for K = 1 to P:
C[I, J] := C[I,J] + A[I, K] * B[K, J]
[End of inner loop.]
[End of Step 2 middie loop.]
[End of Step 1 outer loop,]
5. Exit.

You might also like