Algorithm: InsertElementInArray(dataVal, valArray[], n, k,m)
In this algorithm dataVal is an element which is to be inserted in an array named valArray, whose size is n. we have to insert the element dataVal at index k. m is the total present elements in the array where m<n*considering lower bound of array is 1.
Step 1: [Check for the size of array] if n < k then a) RaiseError "Array Index out of bound" b) goto step 5 Step 2: [Shifting the elements from k indexed elements by 1] i) for index = m to k repeat step a to b a) valArray[index+1] = valArray[index] b) [Decrements counter] index = index - 1 ii) goto to step 3 Step 3: [Now Insert the element] valArray[k] = dataVal; Step 4: Exit
Explanation
Consider size of valArray is 8 ( i.e. n=8), and it contains total 5 elements which are [15,18,12,3,4] at present (i.e. m=5), dataVal =10 which is to be inserted at index 3 (i.e. k=3).
current valArray is
Data 15 18 12 3 4 x x x
Array Index 1 2 3 4 5 6 7 8
since k=3 which is less than n=8 so it will move to step 2
when index = m = 5
Data 15 18 12 3 4 4 x x
Array Index 1 2 3 4 5 6 7 8
when index m = 4
Data 15 18 12 3 3 4 x x
Array Index 1 2 3 4 5 6 7 8
when index = 3 = k
Data 15 18 12 12 3 4 x x
Array Index 1 2 3 4 5 6 7 8
now decrement of index will make index < k so it will now
after execution of step 3:
Data 15 18 10 12 3 4 x x
Array Index 1 2 3 4 5 6 7 8
End
after execution of step 3:
Data 15 18 10 12 3 4 x x
Array Index 1 2 3 4 5 6 7 8
End
No comments:
Post a Comment