Skip to main content

๐Ÿงฉ Insertion Sort

This page provides introduction to Insertion Sort.

Overviewโ€‹

Insertion Sort builds the final sorted array one element at a time. It picks each element from the unsorted portion and places it in its correct position in the sorted portion by shifting larger elements to the right.

Let's sort array below, with insertion sort:

[12,11,13,5,6][12, 11, 13, 5, 6]

Step 1โ€‹

Pick an element from unsorted portion of an array.

insertion-sort-1.svg

Place it in correct position in sorted array.

insertion-sort-2.svg

Step 2โ€‹

Pick an element from unsorted portion of an array.

insertion-sort-3.svg

Place it in correct position in sorted array.

insertion-sort-4.svg

Step 3โ€‹

Pick an element from unsorted portion of an array.

insertion-sort-5.svg

Place it in correct position in sorted array.

insertion-sort-6.svg

Step 4โ€‹

Pick an element from unsorted portion of an array.

insertion-sort-7.svg

Place it in correct position in sorted array.

insertion-sort-8.svg
public void insertionSort(int[] arr) {
for(int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while(j >= 0 && key < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

Complexityโ€‹

Let's say there are N\text{N} elements in an array.

Time Complexityโ€‹

We are inserting an element from unsorted array into sorted array which takes O(N)\text{O}(\text{N}), so total time complexity will be:

O(N2)\text{O}(\text{N}^2)

Space Complexityโ€‹

Algorithm uses constant space.

O(1)\text{O}(1)