Algorithm: To remove element from Array

Algorithm: RemoveElementFromArray(rIndex,valArray[],n,removedData)

In this algorithm rIndex is index from which element is to be removed and n is the size of array valArray. removedData will contain the value which is removed from array from index rIndex.
*consider lower bound of array is 1.

Step 1: [Check for size of array]

           if rIndex > n then

                 a) raise_error "Array Index out of bound"
                 b) Exit
Step 2: removedData = valArray[rIndex]

Step 3: [Shifting elements of array]
           Declare index as integer
           i) for index=rIndex to n-1 repeat step a to b

               a) valArray[index] = valArray[index+1]
               b) index= index+ 1

           ii) valArray[index] = null

Step 4: End


Explanation

Consider size of valArray is 5 ( i.e. n=5), and it contains total 5 elements which are [15,18,12,3,4], and we have to remove element from index 3(i.e. rIndex = 3).


current valArray is

 Data                      15      18          12            3           4
Array Index            1        2           3             4           5

since rIndex = 3 which is less than n=5, so it will move to step 2
at step 2:
removedData = valArray[3] => removedData = 12;

now it will move to step 3:

when index = 3
 Data                      15      18           3             3           4
Array Index            1        2           3             4           5

when index = 4

 Data                      15      18           3             4           4
Array Index            1        2           3             4           5

when index =5 
Control will be exited from loop & will move to step 3(ii)

after the step 


 Data                      15      18           3             4           x
Array Index            1        2           3             4           5

No comments:

Post a Comment