Skip to content

4. Insertion Sort

Insertion sort splits the array into a sorted and unsorted sections. It takes elements and place them at the correct position in the sorted part.

public <T extends Comparable<? super T>> void insertionSort(T[] array) {
    for (int i = 1; i < array.length; i++) {
        int key = array[i];
        int j = i - 1;

        while (j >= 0 && array[j].compareTo(key) > 0) {
            array[j + 1] = array[j];
            j--;
        }

        array[j + 1] = key;
    }
}

This algorithm iterates through the array which takes $O(n)$ and then moves elements which also takes $O(n)$. The time complexity is $O(n^2)$. With space complexity of $O(1)$.

Next Page →