Advertisements
Advertisements
Questions
State algorithm for inserting an element in an Array.
Write an algorithm to insert an element into linear array.
Solution
- Inserting element to an array is the process of adding an element to the existing elements of array.
- The element can be easily inserted at the end of an array. But for insertion in the middle of an array it is required to move the elements one byte forward.
- The following algorithm inserts a data element in an array: Algorithm for inserting element into a linear array:
INSERT [LA, N, K, ITEM]
LA = Linear array
N = Total no. of elements in the array
K = Any positive integer, K<=N
This algorithm inserts an element ITEM into the Kth position in LA.
Step 1: [Initialize Counter]
Set J: = N
Step 2: Repeat steps 3 and 4 while J ≥ K
Step 3: [Move Jth element downward]
Set LA [J+1]: = LA [J]
Step 4: [Decrement Counter]
Set J: = J-1
[End of step 2 loop]
Step 5: [Insert element]
Set LA [K]: = ITEM
Step 6: [Reset N]
Set N: = N+1
Step 7: Exit
Number | 9 is inserted | 4 is deleted |
3 | 3 | 3 |
4 | 4 | 9 |
5 | 9 | 5 |
6 | 5 | 6 |
8 | 6 | 8 |
8 | ||
Original Array | Addition of element in middle array |
Deletion of element from array |