Kodewick
Start learning →
Insertion sort and Shell sort42 / 52

Insertion sort and Shell sort

Lesson 42 of 52 · Part 8 · Sorting · about 15 minutes

Insertion sort slides each item back into place among the sorted ones, like a hand of cards: O(n²), but O(n) on nearly sorted data, so std::sort uses it for pieces of 16 or fewer; Shell sort sorts across a gap that keeps shrinking.

When you sort a hand of cards you don't swap pairs like bubble sort: the cards in your left hand are already in order, you pick up a new one with your right, look back from the end for where it belongs, and slide it in. That's insertion sort. It looks as O(n²) as bubble sort, yet it's the one std::sort really uses: the end of this lesson shows why.

Insertion sort: the front is sorted, slide the next one in

a[0] on its own is sorted. From a[1] on, take out key = a[i], move every bigger one before it back one place, and put key in the gap.

acomparisons 0 · swaps 0sortednot yet1452901234
1int key = a[i], j = i - 1;2while (j >= 0 && a[j] > key) {3    a[j + 1] = a[j];4    j--;5}6a[j + 1] = key;

Inserting key = 2: the 5 and the 4, both bigger, each move back one place, and 2 lands in front of them
Choose one

Insertion sort 5 2 4 6 1 3. After the first 2 passes (2 and 4 inserted), what does the array look like?

In C++: shift, don't swap

In C++, the outer loop runs i from 1 to n − 1, and each pass inserts a[i] into the already sorted a[0..i−1].

The code doesn't actually swap, it shifts: key is taken out first, the bigger ones are copied back one by one, and key is written just once. That's less than half the assignments of a swap each time (one swap is three assignments).

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void insertion_sort(vector<int>& a) {6    int n = a.size();7    for (int i = 1; i < n; i++) {8        int key = a[i];9        int j = i - 1;10        while (j >= 0 && a[j] > key) {11            a[j + 1] = a[j];12            j--;13        }14        a[j + 1] = key;15    }16}17 18int main() {19    vector<int> a = {5, 2, 4, 6, 1, 3};20    insertion_sort(a);21    for (int x : a)22        cout << x << " ";23    cout << "\n";24    return 0;25}
Output
1 2 3 4 5 6 

In the while condition, j >= 0 must come first: && works left to right, so once j is −1 it never reads a[-1].

Fill inTap one to fill a blank; tap a blank to take it back

How far can j go? Fill in the blank so the program sorts 5 2 4 6 1 3.

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {5, 2, 4, 6, 1, 3};7    int n = a.size();8    for (int i = 1; i < n; i++) {9        int key = a[i];10        int j = i - 1;11        while (j >=  && a[j] > key) {12            a[j + 1] = a[j];13            j--;14        }15        a[j + 1] = key;16    }17    for (int x : a)18        cout << x << " ";19    cout << "\n";20    return 0;21}
Change it

Each person has a score and a name, insertion-sorted by score from low to high. The test as written moves people with the same score back too. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).

1#include <iostream>2#include <vector>3using namespace std;4 5struct Item {6    int score;7    char name;8};9 10int main() {11    vector<Item> a = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};12    int n = a.size();13    for (int i = 1; i < n; i++) {14        Item key = a[i];15        int j = i - 1;16        while (j >= 0 && a[j].score  key.score) {17            a[j + 1] = a[j];18            j--;19        }20        a[j + 1] = key;21    }22    for (auto& p : a)23        cout << p.score << p.name << " ";24    cout << "\n";25    return 0;26}
Should print
1B 1D 2A 2C
Exercise 1

Write insertion sort

Fill in insertion_sort: take key out, shift the bigger ones back, then put it in.

It should print
1 2 3 6 7 8
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void insertion_sort(vector<int>& a) {6    int n = a.size();7    for (int i = 1; i < n; i++) {8        int key = a[i];9        int j = i - 1;10        // shift the ones bigger than key back a place, j moving forward; then a[j + 1] = key11    }12}13 14int main() {15    vector<int> a = {8, 3, 6, 1, 7, 2};16    insertion_sort(a);17    for (int x : a)18        cout << x << " ";19    cout << "\n";20    return 0;21}
Output
Press Run or Ctrl+Enter

Fast when it's nearly sorted

How many shifts a pass makes depends on how many before key are bigger. On a sorted array nothing shifts and each pass compares once, n − 1 in all: O(n). On a reversed array each one goes to the very front: O(n²).

Guess the outputA wrong guess is fine

Of these 8 numbers only 6 and 5 are out of order. How many shifts does insertion sort make?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {1, 2, 3, 4, 6, 5, 7, 8};7    int n = a.size(), moves = 0;8    for (int i = 1; i < n; i++) {9        int key = a[i], j = i - 1;10        while (j >= 0 && a[j] > key) {11            a[j + 1] = a[j];12            j--;13            moves++;14        }15        a[j + 1] = key;16    }17    cout << moves << "\n";18    return 0;19}
Choose one

Insertion sort on n numbers that are already sorted: how many comparisons in total?

Choose one

Insertion sort on 2 1 4 3 6 5: how many moves in total?

Exercise 2

Count the inversions

Use insertion sort to count the inversions in the array (pairs where the earlier one is bigger): the number of shifts is the answer. Fill in count_inversions.

It should print
8
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int count_inversions(vector<int> a) {      // by value: it sorts a copy6    int inv = 0;7    // insertion sort, inv++ on every shift8    return inv;9}10 11int main() {12    vector<int> a = {3, 1, 4, 1, 5, 9, 2, 6};13    cout << count_inversions(a) << "\n";14    return 0;15}
Output
Press Run or Ctrl+Enter

Shell sort: compare across a gap, then narrow it

Insertion sort is slow when a small number sits at the end and has to move forward one place at a time. Shell sort first groups by a gap (indexes gap apart form a group) and insertion-sorts each group, so a small number jumps gap places at once; then the gap halves, and at gap = 1 it's plain insertion sort, but by then the array is nearly sorted.

acomparisons 0 · swaps 0987321012345

One pass with gap = 3: indexes 3 apart are compared and swapped if need be, and a small number far back jumps to the front
Choose one

One Shell sort pass with gap = 2 on 5 1 4 2 3. What is the result?

Shell sort in C++

Shell sort's code is almost the same as insertion sort's. This program sorts 10 numbers in reverse order and prints the array after each pass, so you can see it get closer to sorted pass by pass:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5void shell_sort(vector<int>& a) {6    int n = a.size();7    for (int gap = n / 2; gap > 0; gap /= 2) {8        for (int i = gap; i < n; i++) {9            int key = a[i], j = i - gap;10            while (j >= 0 && a[j] > key) {11                a[j + gap] = a[j];12                j -= gap;13            }14            a[j + gap] = key;15        }16        cout << "gap = " << gap << ": ";17        for (int x : a)18            cout << x << " ";19        cout << "\n";20    }21}22 23int main() {24    vector<int> a = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};25    shell_sort(a);26    return 0;27}
Output
gap = 5: 4 3 2 1 0 9 8 7 6 5 
gap = 2: 0 1 2 3 4 5 6 7 8 9 
gap = 1: 0 1 2 3 4 5 6 7 8 9 

Replace every 1 in insertion sort with gap, wrap it in a loop that halves gap from n/2 down to 1, and you have Shell sort. Its complexity depends on the gaps chosen, about O(n^1.3) for the usual ones; it's not stable (equal values can land in different groups and be moved apart).

In exams: given an array and a gap sequence (say 5, 3, 1), write the array after each pass. The method: circle the values whose indexes are gap apart as one group, sort each group on its own, and write them back in their places.

Choose one

With n = 10, which values does for (int gap = n / 2; gap > 0; gap /= 2) give gap, in order?

Choose one

Insertion sort and Shell sort: which one is stable?

With the STL

The STL has no separate insertion_sort, but std::sort uses one all the time. libstdc++'s (g++'s standard library) introsort works in three steps:

  1. it partitions like quicksort, but stops splitting once a piece has 16 or fewer elements, leaving it unsorted;
  2. if the recursion gets too deep (past about 2 log₂ n levels, a sign of a bad input), it heap-sorts that piece instead, which keeps the worst case at O(n log n);
  3. finally it runs one insertion sort over the whole array.

Why step 3 pays off: after partitioning, no number is more than 16 places from where it ends up, so insertion sort shifts each one at most 15 times, O(n) for the whole pass. Carrying on with quicksort on tiny pieces costs more in calls, pivot choices and partitioning than in actual comparisons; insertion sort has no recursion and only walks back through memory, so its constant is small. This program takes 400 numbers, once "fully shuffled" and once "shuffled only within each block of 16" (exactly how partitioning leaves them), and we count insertion sort's shifts:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4#include <random>5using namespace std;6 7// insertion sort, returning how many shifts it made8long long insertion_sort(vector<int>& a) {9    long long moves = 0;10    for (int i = 1; i < (int)a.size(); i++) {11        int key = a[i], j = i - 1;12        while (j >= 0 && a[j] > key) {13            a[j + 1] = a[j];14            j--;15            moves++;16        }17        a[j + 1] = key;18    }19    return moves;20}21 22int main() {23    int n = 400;24    mt19937 g(42);25    vector<int> a(n);26    for (int i = 0; i < n; i++) a[i] = i;27 28    vector<int> r = a;                          // fully shuffled29    shuffle(r.begin(), r.end(), g);30 31    vector<int> s = a;                          // shuffled only within each block of 1632    for (int i = 0; i < n; i += 16)33        shuffle(s.begin() + i, s.begin() + min(i + 16, n), g);34 35    cout << "fully shuffled: " << insertion_sort(r) << " shifts\n";36    cout << "block-shuffled: " << insertion_sort(s) << " shifts\n";37    cout << (is_sorted(r.begin(), r.end()) && is_sorted(s.begin(), s.end()) ? "both sorted" : "not sorted") << "\n";38    return 0;39}
Output
fully shuffled: 39227 shifts
block-shuffled: 1528 shifts
both sorted

Fully shuffled, the shifts are about n²/4; shuffled within blocks, each block takes at most 16 × 15 / 2 = 120, fewer than n/16 × 120 = 7.5n in all: O(n). For the same reason Python's Timsort and Java's sorts also use insertion sort on small runs.

The STL can also write insertion sort in two lines: upper_bound binary-searches the sorted first i elements for where a[i] goes (the first one bigger than it), and rotate turns that range so a[i] lands there and everything between moves back one place. This is binary insertion sort: only O(log i) comparisons per element, but just as many shifts, so still O(n²). upper_bound rather than lower_bound puts equal values after the existing ones, which keeps it stable.

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {5, 2, 4, 6, 1, 3};8    for (int i = 1; i < (int)a.size(); i++) {9        auto pos = upper_bound(a.begin(), a.begin() + i, a[i]);   // binary search for the place10        rotate(pos, a.begin() + i, a.begin() + i + 1);            // turn a[i] into pos11        cout << "i = " << i << ": ";12        for (int x : a) cout << x << " ";13        cout << "\n";14    }15    return 0;16}
Output
i = 1: 2 5 4 6 1 3 
i = 2: 2 4 5 6 1 3 
i = 3: 2 4 5 6 1 3 
i = 4: 1 2 4 5 6 3 
i = 5: 1 2 3 4 5 6 
CallWhat it doesTime
hand-written insertion sortin place, stableO(n) sorted, O(n²) average / worst; shifts = inversions
upper_bound + rotatebinary insertion, stableO(n log n) comparisons, still O(n²) shifts
sort(b, e)introsort: quicksort + heap sort fallback + a final insertion sortO(n log n), not stable
is_sorted(b, e)checks whether it's sortedO(n)

In interviews: "what sort does std::sort use": introsort, and say what each of its three parts is for: quicksort for the average case, heap sort for the worst case, insertion sort for the small pieces. If asked "why insertion sort for small pieces": for small n, n² and n log n are close, insertion sort has no recursion and a small constant, and it's O(n) on nearly sorted data.

Guess the outputA wrong guess is fine

One step of binary insertion: put a[3] = 3 into the already sorted 2 5 7. What is printed?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {2, 5, 7, 3, 9};8    int i = 3;9    auto pos = upper_bound(a.begin(), a.begin() + i, a[i]);10    cout << pos - a.begin() << ": ";11    rotate(pos, a.begin() + i, a.begin() + i + 1);12    for (int x : a)13        cout << x << " ";14    cout << "\n";15    return 0;16}

Summary

Take-away

Insertion sort: pick one up, slide it back into place

  • The front is sorted; bigger ones shift back, key is written once
  • O(n) when sorted, O(n²) reversed; shifts = inversions; stable
  • Shell: insertion sort by gap groups, the gap halving down to 1; not stable
  • std::sort stops splitting at 16 or fewer, then one insertion sort over everything, O(n)
1int key = a[i], j = i - 1;2while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }3a[j + 1] = key;4rotate(upper_bound(a.begin(), a.begin() + i, a[i]), a.begin() + i, a.begin() + i + 1);