17665607061631782734693985282237.gif

Idea: Insert each element into its correct position

When to use


public class InsertionSort {
    public static void sort(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int key = a[i];
            int j = i - 1;
            while (j >= 0 && a[j] > key) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = key;
        }
    }
}

Watch for

Mental model: šŸƒ Insert into correct position