Sorting Algorithms in C++
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? +
What is the difference between std::sort and std::stable_sort? +
See it in motion
Watch this algorithm and 9 others run step by step in our free interactive visualizer.
▶ Launch Visualiser