C Insertion Sort

Summary: this tutorial introduces you to insertion sort algorithm and how to implement the insertion sort in C.

Introduction to insertion sort algorithm

Insertion sort in CIn the insertion sort algorithm, we sort a unsorted array by inserting its elements to the proper positions in a sorted array. The insertion sort algorithm is efficient in case the array is substantially sorted. It is more efficient to use the quicksort or heapsort algorithm to sort a big list of unsorted elements.

When we sort something manually, we often use the insertion sort technique e.g., when we sort a deck of playing cards. We can describe the insertion sort algorithm similar to sort a deck of playing cards:

  1. First, we start with an empty set of cards (on our hand i.e., the sorted array) and the cards on the table i.e., the unsorted array.
  2. Then we pick one card at a time from the table i.e., unsorted array,  and insert it into the proper position in our hand  i.e., the sorted array
  3. In order to insert a card in the correct position, we compare it with the existing cards in our hand from right to left.

Notice that the cards that we hold are always sorted.

The complexity of the insertion sort algorithm is О(n2) where n is the number of elements that need to be sorted.

C insertion sort algorithm implementation

The following is the program that demonstrates the insertion sort in C.

In this tutorial, we have explained the insertion sort algorithm and shown you how to implement the insertion sort in C.