C program to sort array elements using insertion sort

Posted on 20th April 2015

Insertion sort algorithm iterates through the array sorting one element at a time. The array is split into two sub arrays as it iterates - one sub array contains the sorted elements and the other contains the unsorted items. This is exactly like sorting a set of playing cards where you pick up one card at a time and puts it in the right position.

The iteration starts by comparing the second element of the array to the first. If the second element is less than the first then the two elements are swapped.

In the next iteration, the third element is first compared to second element, if the third element is smaller then it is swapped with the second element. Then it is compared to the first element and swapped if smaller than the first.

In general, the element that is picked up is compared to each element before it until its correct position is located.

Insertion sort is a very efficient algorithm for sorting smaller arrays. It requires n-1 iterations to sort an array containing n elements. In the best case, the maximum number of comparisons required is the sum of n-1 numbers.

Here is a C program that takes the elements of an array as input, sort it using Insertion sort algorithm and prints the sorted array.