3 Arrays Copy
3 Arrays Copy
By
Amit Sharma
Asst. Professor,
Lovely Professional University, Punjab
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
Implementation of Linear Array in
Memory
Location of A[K]=BASE[A]+W[K-LB]
BASE[A] - Base address of array.
(The address of the first reserve location for the array is called
Base address of the array.)
K is the position of any element in the array
LB – Lower Bound.
W = 1 for Character.
W = 2 for Integer.
W = 4 for Float.
Question
• An array ‘A’ consist of 5 character elements, Calculate
locations of the elements, The base address in 2001.
A[0],A[1],A[2],A[3],A[4]
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 at the End of Linear Array
1. Dimension of A is M.
2. Repeat for I=0 to N-1.
Read A[I]
3. Set A[N]=data [(N-1)+1]=N
4. Repeat for I=0 to N.
5. END
Insertion into a Linear Array
• Algorithm: (Consider an array ‘A’ that can store maximum of
M elements. At present array is having N number of elements,
such that N<M. To insert an element NEW at the Kth position
Kth place where K<N)
1. Set DATA=A[K]
2. Repeat for J = K to N-1.
3. [Move (J+1)th element upward] Set A[J] = A[J+1].
[End of loop.]
4. [Reset the number of elements N] Set N = N-1.
5. Exit
Merging Algorithm
14
Merging Algorithm
Algorithm: Merging (A, R,B,S,C)
Here A and B be sorted arrays respectively. This algorithm merges A and B
into an array C.
Step 5: Exit
16
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)
17
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)