C++ · Module 18 · Lesson 62 min read

Sorting & Searching Implementations

Simple sorts — O(n²)

AlgorithmIdeaNotes
Bubble sortswap adjacent pairs, repeatteaching only
Selection sortpick the minimum, put it firstfewest swaps
Insertion sortinsert each element into the sorted prefixfast for small or nearly-sorted data ✅, stable

Divide and conquer — O(n log n)

Merge sort

  1. Split in half, sort each half recursively
  2. Merge two sorted halves
  • Always O(n log n), stable, needs O(n) extra memory
  • Great for linked lists and external (on-disk) sorting

Quicksort

  1. Choose a pivot, partition: smaller left, larger right
  2. Recursively sort both parts
  • Average O(n log n), in place, very fast in practice
  • Worst case O(n²) with bad pivots (e.g. always first element on sorted data) → use the middle/random/median-of-three pivot

Heap sort

Build a max-heap, repeatedly move the max to the end. O(n log n) worst case, in place, not stable.

Comparison

AlgorithmBestAverageWorstExtra spaceStable
InsertionO(n)O(n²)O(n²)O(1)✅
MergeO(n log n)O(n log n)O(n log n)O(n)✅
QuickO(n log n)O(n log n)O(n²)O(log n)❌
HeapO(n log n)O(n log n)O(n log n)O(1)❌
Counting sortO(n + k)O(k)✅ (small integer ranges)

Binary search pitfalls

  • Midpoint: lo + (hi - lo) / 2 (avoids overflow of lo + hi)
  • Decide between [lo, hi] and [lo, hi) and be consistent
  • Works only on sorted data

In real code: std::sort, std::stable_sort, std::lower_bound ✅

Example

C++
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>

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

void merge_sort(std::vector<int>& a, std::vector<int>& tmp, std::size_t lo, std::size_t hi) {   // [lo, hi)
    if (hi - lo < 2) return;
    std::size_t mid = lo + (hi - lo) / 2;
    merge_sort(a, tmp, lo, mid);
    merge_sort(a, tmp, mid, hi);
    std::size_t i = lo, j = mid, k = lo;
    while (i < mid && j < hi) tmp[k++] = (a[j] < a[i]) ? a[j++] : a[i++];   // <= keeps it stable
    while (i < mid) tmp[k++] = a[i++];
    while (j < hi) tmp[k++] = a[j++];
    std::copy(tmp.begin() + static_cast<long>(lo), tmp.begin() + static_cast<long>(hi), a.begin() + static_cast<long>(lo));
}

void quick_sort(std::vector<int>& a, int lo, int hi) {        // [lo, hi]
    if (lo >= hi) return;
    int pivot = a[lo + (hi - lo) / 2];                         // middle pivot avoids sorted-input worst case
    int i = lo, j = hi;
    while (i <= j) {
        while (a[i] < pivot) ++i;
        while (a[j] > pivot) --j;
        if (i <= j) std::swap(a[i++], a[j--]);
    }
    quick_sort(a, lo, j);
    quick_sort(a, i, hi);
}

int binary_search(const std::vector<int>& a, int target) {
    int lo = 0, hi = static_cast<int>(a.size()) - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;                          // no overflow
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
    }
    return -1;
}

int main() {
    std::vector<int> sample = { 38, 27, 43, 3, 9, 82, 10 };
    auto a = sample, b = sample, c = sample;
    insertion_sort(a);
    std::vector<int> tmp(b.size());
    merge_sort(b, tmp, 0, b.size());
    quick_sort(c, 0, static_cast<int>(c.size()) - 1);
    std::cout << "insertion:";
    for (int x : a) std::cout << ' ' << x;
    std::cout << "\nmerge:    ";
    for (int x : b) std::cout << ' ' << x;
    std::cout << "\nquick:    ";
    for (int x : c) std::cout << ' ' << x;
    std::cout << '\n';
    std::cout << "binary_search 43 -> index " << binary_search(c, 43) << ", 50 -> " << binary_search(c, 50) << '\n';

    std::mt19937 rng(2026);                                    // fixed seed: reproducible test data
    std::uniform_int_distribution<int> dist(0, 1'000'000);
    std::vector<int> big(200'000);
    for (int& x : big) x = dist(rng);
    auto expected = big;
    std::sort(expected.begin(), expected.end());
    auto m = big, q = big;
    std::vector<int> t2(m.size());
    merge_sort(m, t2, 0, m.size());
    quick_sort(q, 0, static_cast<int>(q.size()) - 1);
    std::cout << std::boolalpha << "200,000 random values: merge correct? " << (m == expected)
              << ", quick correct? " << (q == expected) << '\n';

    std::vector<int> already_sorted(100'000);
    for (int i = 0; i < 100'000; ++i) already_sorted[i] = i;
    quick_sort(already_sorted, 0, 99'999);                      // middle pivot: still fast
    std::cout << "quick sort on sorted input finished, still sorted? "
              << std::is_sorted(already_sorted.begin(), already_sorted.end()) << '\n';
    return 0;
}

/* Output:
insertion: 3 9 10 27 38 43 82
merge:     3 9 10 27 38 43 82
quick:     3 9 10 27 38 43 82
binary_search 43 -> index 5, 50 -> -1
200,000 random values: merge correct? true, quick correct? true
quick sort on sorted input finished, still sorted? true
*/