Language Implementations

Sorting Algorithms in C++

Updated June 8, 2026 7 min read

C++ gives you the fastest standard-library sorting of any mainstream language, along with fine-grained control. This guide covers std::sort and its relatives, the Introsort algorithm behind them, and clean implementations of the classics.

The standard sorts

std::sort(begin, end) uses Introsort (Quick Sort + Heap Sort + Insertion Sort) for guaranteed O(n log n) — fast but not stable. std::stable_sort preserves equal-element order (Merge Sort based). std::sort_heap and std::partial_sort cover heap-based and top-k needs. Pass a comparator: std::sort(v.begin(), v.end(), std::greater<>()).

Why std::sort is so fast

Introsort gets Quick Sort's cache-friendly speed, switches to Heap Sort to avoid the O(n²) worst case, and finishes with Insertion Sort on small partitions. Combined with C++'s zero-overhead abstractions and inlined comparators, it is the gold standard for in-memory sorting. See what std::sort uses.

Quick Sort in C++

void quickSort(std::vector<int>& a, int lo, int hi) {
    if (lo < hi) {
        int p = partition(a, lo, hi);
        quickSort(a, lo, p - 1);
        quickSort(a, p + 1, hi);
    }
}

Frequently asked questions

What algorithm does C++ std::sort use? +
std::sort typically uses Introsort — a hybrid of Quick Sort, Heap Sort, and Insertion Sort that guarantees O(n log n). It is not stable; use std::stable_sort when you need stability.
What is the difference between std::sort and std::stable_sort? +
std::sort uses Introsort and is not stable but is faster. std::stable_sort preserves the relative order of equal elements (Merge Sort based) at the cost of O(n) memory.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles