Here’s a “fast” in‑place QuickSort implementation in C++ that combines three classic optimizations:
- Median‑of‑three pivot selection to avoid pathological pivots
- Insertion sort for small partitions (here, size ≤ 16)
- Tail‑recursion elimination to bound stack depth
This typically runs in O(n log n) time and is very competitive in practice.
#include <iostream>
#include <vector>
#include <algorithm> // for std::swap
// Insertion sort for small subarrays [l…r]
template<typename T>
void insertion_sort(std::vector<T>& A, int l, int r) {
for (int i = l + 1; i <= r; ++i) {
T key = std::move(A[i]);
int j = i - 1;
while (j >= l && A[j] > key) {
A[j + 1] = std::move(A[j]);
--j;
}
A[j + 1] = std::move(key);
}
}
// Return index of median of A[a], A[b], A[c]
template<typename T>
int median_of_three(std::vector<T>& A, int a, int b, int c) {
if (A[a] < A[b]) {
if (A[b] < A[c]) return b;
else if (A[a] < A[c]) return c;
else return a;
} else {
if (A[a] < A[c]) return a;
else if (A[b] < A[c]) return c;
else return b;
}
}
// In-place QuickSort with optimizations
template<typename T>
void fast_quick_sort(std::vector<T>& A, int l, int r) {
while (l < r) {
// Use insertion sort for small partitions
if (r - l + 1 <= 16) {
insertion_sort(A, l, r);
break;
}
// Median‑of‑three pivot selection
int m = l + (r - l) / 2;
int pivot_idx = median_of_three(A, l, m, r);
T pivot = A[pivot_idx];
std::swap(A[pivot_idx], A[r]); // move pivot to end
// 2‑way partitioning
int i = l, j = r - 1;
while (i <= j) {
while (i <= j && A[i] < pivot) ++i;
while (i <= j && A[j] > pivot) --j;
if (i < j) std::swap(A[i++], A[j--]);
}
std::swap(A[i], A[r]); // place pivot in position
// Recurse on smaller half first to limit stack depth
if (i - 1 - l < r - (i + 1)) {
fast_quick_sort(A, l, i - 1);
l = i + 1; // tail‑call elimination on the larger half
} else {
fast_quick_sort(A, i + 1, r);
r = i - 1; // tail‑call elimination
}
}
}
// Convenience wrapper
template<typename T>
void fast_sort(std::vector<T>& A) {
if (!A.empty())
fast_quick_sort(A, 0, int(A.size()) - 1);
}
// Example
int main() {
std::vector<int> data = { 9,3,5,1,8,7,2,6,4,0,15,11,12,13,14 };
fast_sort(data);
for (auto x : data) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Explanation of key points:
- Median‑of‑three (lines 23–34) picks the pivot from the first, middle and last elements.
- Insertion sort (lines 5–16) is used for tiny partitions (≤16 items) because it’s faster than recursive QuickSort on small arrays.
- Tail‑recursion elimination (lines 42–52) always recurses first on the smaller half, then loops back to sort the larger half, keeping recursion depth to O(log n).
This hybrid runs in Θ(n log n) on average, uses O(log n) stack space, and is very cache‑friendly.