Code insertionSort(int a[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
Algorithm
Start
Start a for loop till it reaches ‘n’
Select the ith element from the array and
assign it to key
Compare the key with the i-1 element in the
array
If it is greater then swap the ith element and
i-1 element. Then decrement i.
If it is not greater continue with for loop and
change the key.
Repeat the above 4 steps till for loop fails
8 2 4 9 3 6
8 2 4 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
Best case complexity : O(n)
Worst case complexity : O(n2)