Algo-Sim › Sorting & Divide and Conquer

Insertion Sort

Easy · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input

Grow a sorted prefix: take the next value and shift bigger ones right until it fits. Fast on nearly sorted input.

Problem

Sort nums into ascending order with insertion sort: grow a sorted prefix one value at a time, shifting larger values right to open a slot for each new value.

Constraints

Edge cases to test

Follow-up questions

Why do real sorts use it for small arrays?
Low overhead and good cache behaviour: Timsort and introsort switch to insertion sort below about 16–32 elements.
How is it tied to inversions?
Its running time is O(n + inversions): each shift fixes exactly one inversion.

Solution

Java

public int[] insertionSort(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        int key = nums[i];
        int j = i - 1;
        while (j >= 0 && nums[j] > key) {
            nums[j + 1] = nums[j];
            j--;
        }
        nums[j + 1] = key;
    }
    return nums;
}

Python

def insertion_sort(nums):
    for i in range(1, len(nums)):
        key = nums[i]
        j = i - 1
        while j >= 0 and nums[j] > key:
            nums[j + 1] = nums[j]
            j -= 1
        nums[j + 1] = key
    return nums

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> insertionSort(vector<int> &nums) {
        for (int i = 1; i < int(nums.size()); i++) {
            int key = nums[i];
            int j = i - 1;
            while (j >= 0 && nums[j] > key) {
                nums[j + 1] = nums[j];
                j--;
            }
            nums[j + 1] = key;
        }
        return nums;
    }
};

More Sorting & Divide and Conquer problems