English

State algorithm for inserting an element in an Array. - Computer Science 1

Advertisements
Advertisements

Questions

State algorithm for inserting an element in an Array.

Write an algorithm to insert an element into linear array. 

Long Answer

Solution

  1. Inserting element to an array is the process of adding an element to the existing elements of array.
  2. 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.
  3. 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
shaalaa.com
Basic Data Structures (Stack, Queue, Dequeue)
  Is there an error in this question or solution?
2015-2016 (March)
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×