Summary: In this tutorial, we will learn what Insertion sort algorithm is and how to implement the Insertion sort algorithm to sort an array in C and Java.

Introduction to Insertion sort Algorithm

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.

Wikipedia

Insertion sort is a stable sorting algorithm that is used to sort linear data structures such as array and list.

The algorithm sorts array elements one by one. On each iteration, the sorted partition of the array grows and the unsorted partition shrinks.

Insertion Sort Visualization

The black blocks represent the sorted partition and otherwise represent the unsorted partition of the array.

In the above example, the Insertion sort algorithm picks one element (red block) at a time and place it to its correct position in the sorted partition.

The algorithm repeats this process for every element and in the end, the array is sorted.

Insertion Sort Algorithm

Steps to implement Insertion Sort Algorithm:

  1. Loop from i=1 to i<array.length
  2. Select array[i] and assign pos=i.
  3. Nest another Loop from j=i-1 to j>=0
  4. Check if(array[i] < array [j]).
  5. If yes then shift array[j] to the right (i.e. array[j+1]=array[j]) and assign pos=j.
  6. If not then assign pos=j+1 break the nested loop.
  7. End nested j loop.
  8. Assign array[i] to index position pos (i.e. array[pos]=array[i]).
  9. End i loop.

Here step-2 is selecting the array element and step-3 to step-7 shift all the elements to the right which are greater than the selected element.

Finally, step-8 places the selected element to its correct position.

Here is the implementation of the insertion sort algorithm in C and Java.

C

Java

Output

Unsorted array
8 36 -51 9 21 46 2
Sorted array
-51 2 8 9 21 36 46


In the above program, the temp variable stores the copy of the selected element because on right swapping the greater elements its value gets overwritten in the array.

The pos variable, stores the correct position of the selected array element.

Insertion Sort Overview

  • In-place algorithm – No extra array is needed.
  • O(n²) time complexity – quadratic.
  • Stable algorithm – Doesn’t interchange the same values in the array.
  • Quite Efficient for data sets that are already substantially sorted.

In this tutorial, we learned what Insertion sort algorithm is and how to implement Insertion sort algorithm to sort an array in C and Java programming languages.

Leave a Reply