std::nth_element
std::nth_element rearranges a random-access range so the element at nth is the one that would be there after a full sort. Every element before nth is not greater than it; every element after is not less. Average time is O(n).
Detailed Explanation
You need the median, or the 10th smallest score, and you do not need the rest sorted. Full sort is O(n log n). nth_element(first, nth, last) is the selection algorithm (usually introselect: quickselect with a heapsort fallback). After it returns, *nth is the correct order statistic. The two sides are partitioned, not sorted.
To get the median of an odd-length vector: nth_element(v.begin(), v.begin() + v.size()/2, v.end());. For the k smallest elements in any order, pass v.begin() + k as nth; the prefix [begin, nth) holds them. If you then need that prefix sorted, sort only the prefix.
The comparator has the same strict-weak-ordering rules as sort. Equal elements can sit on either side of nth as long as they are equivalent to *nth or correctly less/greater.
Worst-case of naive quickselect is O(n²). The standard requires linear average complexity; quality implementations use median-of-medians or introspective fallback so the worst case is O(n log n) or O(n). Do not reimplement quickselect without that fallback and then sort a million adversarial items.
nth_element is in-place and not stable. It shuffles the range. If you need the original order, copy first.
partial_sort(first, middle, last) puts the smallest middle - first elements in sorted order in the prefix, and is more expensive than nth_element (roughly O(n log k)). Use nth_element when you only need the kth or an unordered set of k, and partial_sort when the k must be sorted.
C++20 std::ranges::nth_element(v, v.begin() + k) and projections work as with sort.
There is no nth_element on a list. Copy to a vector, or use list::sort if you needed a full order anyway.
Code Examples
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{9, 1, 7, 3, 5};
auto mid = v.begin() + static_cast<std::ptrdiff_t>(v.size() / 2);
std::nth_element(v.begin(), mid, v.end());
std::cout << *mid << '\n'; // prints: 5 (median)
std::vector<int> w{9, 1, 7, 3, 5};
std::nth_element(w.begin(), w.begin() + 2, w.end());
// the three smallest are in w[0..2], unsorted
}#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
int kthSmallest(std::vector<int> v, std::size_t k) {
std::nth_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(k), v.end());
return v[k];
}
int main() {
std::cout << kthSmallest({4, 1, 8, 3}, 1) << '\n'; // prints: 3
}Common Gotchas
`nth` must be in `[first, last]`
`nth_element(v.begin(), v.end(), v.end())` is not a valid nth (the standard requires `nth` in `[first, last]`). For "largest", use `v.end() - 1`.
The prefix is not sorted
do not binary-search it. `sort` the prefix if you need order.
It mutates the range
pass a copy if callers still need the original sequence.
k out of range
`kthSmallest` must reject `k >= v.size()` before forming the iterator.