sorting

Rank, selection, bubble and insertion sort are developed in the performance chapter, then bin sort and radix sort in the linear list chapter Sorting is not one algorithm It is a family of tradeoffs

Insertion sort

#include <vector>

std::vector<int> insertion_sort(std::vector<int> items) {
    for (std::size_t i = 1; i < items.size(); ++i) {
        int key = items[i];
        long j = static_cast<long>(i) - 1;
        while (j >= 0 && items[j] > key) {
            items[j + 1] = items[j];
            --j;
        }
        items[j + 1] = key;
    }
    return items;
}

On [5, 2, 9, 1] it returns [1, 2, 5, 9]

The mental model is a hand of cards You pick one card and slide it left until it sits in the right place If the hand is nearly sorted, each card moves only a little

That is why insertion sort is not a joke It is excellent for small or nearly sorted input It is terrible for large reversed input, which is what your test data will be if you generate it with a descending loop

Merge sort

std::vector<int> merge_sort(const std::vector<int> &items) {
    if (items.size() <= 1) return items;
    auto mid = items.size() / 2;
    auto left = merge_sort(std::vector<int>(items.begin(), items.begin() + mid));
    auto right = merge_sort(std::vector<int>(items.begin() + mid, items.end()));
    std::vector<int> out;
    out.reserve(items.size());
    std::size_t i = 0, j = 0;
    while (i < left.size() && j < right.size()) {
        if (left[i] <= right[j]) out.push_back(left[i++]);
        else out.push_back(right[j++]);
    }
    while (i < left.size()) out.push_back(left[i++]);
    while (j < right.size()) out.push_back(right[j++]);
    return out;
}

Split until each piece is trivial Merge by always taking the smaller head The merge step is where the work happens

Two philosophies

Insertion sort makes one pass and keeps a growing sorted prefix Merge sort splits the problem and pays to combine

The first is simple and adaptive The second is predictable and memory hungry

Stability

A stable sort keeps the relative order of equal keys Insertion sort with > is stable This merge is stable because it takes from the left on ties

That detail matters when you sort records by one field and quietly expect another field to keep its order Quiet expectations are how bugs get promoted

Memory

Merge sort allocates helper vectors Insertion sort sorts in place On a large log file that difference is real

What to use

std::sort in real code Learn these to understand tradeoffs, not to replace the standard library A production sort has been tuned for years by people who care about cache behaviour more than you do

Mistakes

  • comparing with >= and losing stability without noticing
  • assuming the input vector can be mutated when the caller still needs it
  • sorting strings and numbers together and expecting numeric order
  • measuring once and declaring a winner

Exercises

  1. Run both sorts on sorted, reversed and random vectors
  2. Change insertion sort to descending and keep it stable
  3. Explain why merge sort needs helper memory
  4. Find a sort call in a tool you use and check whether it mutates input

What to remember

Sorting is about the shape of the input as much as the algorithm Ask what the data looks like before you ask which sort is fastest

Posted