Insertion sort

Working of Insertion sort

Insertion sort is sorting mechanism which is best then both bubble sort and selection sort. The elements in the array are compared with the preceding elements.

In insertion sort array zeroth element is declared to be the sorted element, next element(first index) assume it as a key element, it is compared with its preceding elements one by one If any element in the preceding elements found to be greater than the key element then the key element will be shifted to the greater element index place and the greater element and its next elements move one step right(the index number of the greater element and its next elements will be increased by 1).

Insertion sort
  • here, in the example above 7 is declared to be sorted, so the comparison will start from the next element 6
  • In step1, the 1st index element 6 is compared with the left side values in its array and takes its respective place after comparing the values of left side array elements
  • In step2, the 2nd index element 5 is compared with its left side elements and will be inserted in its appropriate place
  • Likewise, the iterations will be done until all elements in the array are sorted

The Time complexity of Insertion Sort

  • Worst Case Time Complexity [ Big-O ]: O(n2)
  • Best Case Time Complexity [Big-omega]: O(n)
  • Space Complexity: O(1)

Program for Insertion sort

void insertionsort(int a[],int n)
int j,p;
int tmp;
for(j=p;j>0 && a[j-1] > tmp; j--)
int main()
int i,n,a[10];
printf("enter no of elemnts");
printf("enter the elemnts ");
printf("the sorted elements are");
return 0;
Last updated on by vishal devxo