Professional Documents
Culture Documents
Mehak
UID: 23837
SEEE-CSE
Introduction
* Complexity: O(n)
Example 1
ALGORITHM: This algorithm inserts an element ITEM into the Kth position in LA.
Elements are being moved downward to create space for new item.
N: size of an array(say 5) and K: where you want to add item(say 3 rd)
A 1 A 1
B 2 B 2
C 3 E 3
D 4 C 4
5 D 5
6 6
Solution:
Algorithm: To insert an E at 3rd position
Step 1: Set i = N=4 [counter initialization]
Step 2: Repeat step 3 and 4 while[i >=K]
[loop]
where K=3
Step 3: LA[i+1] = LA[i]
Step 4: i = i-1
[end loop]
Step 5: Set LA[3] = E(ITEM)
Step 6: N = N+1 //4 = 5, i.e. increasing the index number
Step 7: EXIT
Deletion Algorithm
(Deleting from a linear array) DELETE (LA, N, K, ITEM)
ALGORITHM: This algorithm deletes the Kth element from LA. Here LA
is a linear array with N elements and K is a positive integer such that
K <= N
*Complexity: O(n)
Example
• A linear array(LA) has 4 elements(A,B,C,D) where
LB=1 and UB=4. Write an algorithm to delete an
element B at 2nd position.
A 1
C 2
D 3
4
5
6
Solution:
Step 1: Set NA=1, NB=1 and PTR=1 [initialize the counters for A,B,C]
Step 2: Repeat while NA <= R and NB <= S:
if A[NA] ≤ B[NB], then:
(a) Set C[PTR] = A[NA] //assign element from A to C
(b) Set PTR = PTR+1 and NA = NA +1 //update
pointers
else
(a) Set C[PTR] = B[NB] //assign elements
from B to C
(b) Set PTR = PTR+1 and NB = NB +1 //update pointers
[End of if structure]
[End of Loop]
23
Merging Algorithm
Step 4: Exit
24
Complexity of Merge algorithm
•
Algorithm:
Step 1: Set DATA[N+1] = ITEM [insert ITEM at the end of the DATA]
Step 2: Set LOC =1 [counter initialization]
Step 3: Repeat while DATA[LOC] ITEM: [till location of ITEM is not found]
Set LOC = LOC + 1
[end of loop]
Step 4: [Successful ?] If LOC = N+1, then Set LOC = 0
Step 5: Exit
**
•
Since Paula appears at (N+1) th location, thus Paula is not in the
original array.
B. Binary Search
• During each stage of binary search, search for ITEM is reduced to
segments of the DATA.
• Then, algorithm compares the ITEM with the middle element of the
segment, DATA[MID], where MID is obtained by:
• If DATA[MID] = ITEM, then search is successful and we set LOC=MID;
otherwise new segment of DATA is obtained as:
Algorithm:
Each comparison reduces the sample size in two
halves, therefore maximum number of comparisons
required to locate ITEM is:
or
• Length = UB – LB + 1