Given the sequence 9 2 3 8 7 4 5 6 List all the element comp
Solution
In Insertion Sort, let A[i] is current element and A[j] is the next element in the array.
For each element A[i], if A[i]>A[j], swap the elements until A[i]<=A[j].
Solution:
Given Array of Elements: [ 9,2,3,8,7,4,5,6]
Step 1: A[i]=9, A[j]=2, As A[i]>A[j], so swap the elements, so new updated array is: [2,9,3,8,7,4,5,6]
Step 2: A[i]=9, A[j]=3, As A[i]>A[j], so swap the elements, so new updated array is: [2,3,9,8,7,4,5,6]
Step 3: A[i]=9, A[j]=8, As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,9,7,4,5,6]
Step 4: A[i]=9, A[j]=7, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,9,4,5,6]
Step 5: A[i]=9, A[j]=4, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,4,9,5,6]
Step 6: A[i]=9, A[j]=5, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,4,5,9,6]
Step 7: A[i]=9, A[j]=6, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,4,5,6,9]
NOTE: As per insertion sort logi 2 and 3 are at the correct position, so there is no need to compare them with other elements, so next element to be compared is 8.
Step 8: A[i]=8, A[j]7=, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,7,8,4,5,6,9]
Step 9: A[i]=8, A[j]=4, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,7,4,8,9,5,6]
Step 10: A[i]=8, A[j]=9, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,7,4,8,9,5,6]
Step 11: A[i]=9, A[j]=5, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,4,5,9,6]
Step 12: A[i]=9, A[j]=6, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,8,7,4,5,6,9]
Step 13: A[i]=8, A[j]=7, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,7,8,4,9,5,6]
Step 14: A[i]=8, A[j]=4, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,7,4,8,9,5,6]
Step 15: A[i]=7, A[j]=4, as As A[i]>A[j], so swap the elements, so new updated array is: [2,3,4,7,8,9,5,6]
Now we have to place 5, 6 as per the sorted element list so performing the comparision of element 5 and 6 with the 7,8,9, we get the answer as follow:
So the sorted array is : [2,3,4,5,6,7,8,9]
