Professional Documents
Culture Documents
3 Arrays
3 Arrays
3 Arrays
Data Structures
Lecture : Linear Array
Contents
• Basic Terminology
• Linear Array
• Memory Representation of Linear Array
• Traversing Array
• Insertion and Deletion in Array
• Sorting (Bubble Sort)
• Searching (Linear Search and Binary Search)
• Review Questions
Basic Terminology
• Linear Data Structures: A data structure is said to be linear if its
elements form a sequence or a linear list.
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
Traversing Linear Array
• Suppose we have to count the number of element is an array
or print all the elements of array.
1. Repeat for K = LB to UB
Apply PROCESS to A[K].
[ End of Loop.]
2. Exit.
Question 2: Find out the sum of all the two digit numbers in an
array.
Insertion and Deletion in an Array
• Two types of insertion are possible:
• Insertion at the end of array
• Insertion in the middle of the array
Insertion into a Linear Array
• Algorithm: (Insertion of an element ITEM into Kth position in
a Linear Array A)
11
Merging Algorithm
Algorithm: Merging (A, R,B,S,C)
Here A and B be sorted arrays with R and S elements
respectively. This algorithm merges A and B into an array
C with N=R+ S elements
Step 1: Set NA=0, NB=0 and NC=0
Step 2: Repeat while NA < R and NB < S:
if A[NA] ≤ B[NB], then:
Set C[NC] = A[NA]
Set NA = NA +1
else
Set C[NC] = B[NB]
Set NB = NB +1
[End of if structure]
Set NC= NC +1
[End of Loop]
12
Merging Algorithm
Step 3: If NA >=R, then:
Repeat while NB < S:
Set C[NC] = B[NB]
Set NB = NB+1
Set NC = NC +1
[End of Loop]
else
Repeat while NA < R:
Set C[NC] = A[NA]
Set NC = NC + 1
Set NA = NA +1
[End of loop]
[End of if structure]
Step 4: Return C[NC]
13
Merging Algorithm
• Complexity of merging: The input consists of the total number
n=r+s elements in A and B. Each comparison assigns an
element to the array C, which eventually has n elements.
Accordingly, the number f(n) of comparisons cannot exceed n:
f(n) ≤ n = O(n)
14
Searching
1. Linear Search:
• Compares the item of interest with each element of Array
one by one.
• Traverses the Array sequentially to locate the desired
item.
Linear Search Algorithm
• LINEAR (DATA, N, ITEM, LOC)