Sub topic 11
Using std::nth_element and numpy.partition
Earlier chapters built quickselect by hand. In production code you will rarely do that. C++ and NumPy both ship tuned selection routines built on the same ideas: partitioning, one-sided recursion, and a fallback that protects against bad pivots. This chapter covers how to call them correctly, what they promise and what they leave out, and the mistakes people commonly make with them.
This chapter assumes you know zero-based indexing, Big-O notation, the quickselect loop, and introselect from the previous chapters. For the C++ sections you should know iterators and how to compile a short program (C++17 or later). For the NumPy sections you should know how to create arrays and slice them.
What Both Functions Promise
Both functions solve the selection problem in place, or on a copy, and they make the same guarantee. Given a position k, after the call:
- The element at index
kis the one that would sit there if the whole range were sorted. - Every element before index
kis less than or equal to it. - Every element after index
kis greater than or equal to it.
That is the full contract. Neither function promises any order inside the left part or the right part. If you print the whole array afterward, you will see something that looks partly shuffled, and the exact arrangement can change between library versions, compilers, and runs.
std::nth_element in C++
Signature and basic use
The function lives in <algorithm>:
template <class RandomIt>
void nth_element(RandomIt first, RandomIt nth, RandomIt last);
template <class RandomIt, class Compare>
void nth_element(RandomIt first, RandomIt nth, RandomIt last, Compare comp);You pass the range [first, last) and an iterator nth that points at the position you want filled correctly. The function returns nothing and rearranges the range in place. C++17 adds overloads that take an execution policy as the first argument, and C++20 adds std::ranges::nth_element, which accepts a whole container and an optional projection.
The program below shows the three most common uses: the k-th smallest element, the k-th largest using a reversed comparator, and a median.
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <vector>
int main() {
// 1. k-th smallest (0-based)
std::vector<int> v{9, 1, 8, 2, 7, 3};
std::size_t k = 2;
std::nth_element(v.begin(), v.begin() + k, v.end());
std::cout << "3rd smallest: " << v[k] << '\n'; // 3
// 2. k-th largest: reverse the ordering
std::vector<int> w{9, 1, 8, 2, 7, 3};
std::nth_element(w.begin(), w.begin() + 1, w.end(), std::greater<int>());
std::cout << "2nd largest: " << w[1] << '\n'; // 8
// 3. Median of an even-length vector
std::vector<int> m{7, 1, 5, 3, 9, 2};
std::size_t n = m.size();
auto mid = m.begin() + n / 2;
std::nth_element(m.begin(), mid, m.end());
int upper = *mid;
// Everything before mid is <= upper, so the lower median is the max of that part.
int lower = *std::max_element(m.begin(), mid);
std::cout << "median: " << (lower + upper) / 2.0 << '\n'; // 4
return 0;
}Compile with g++ -std=c++17 -O2 select.cpp -o select. The median trick in part 3 needs only one call to nth_element. After it, the left half holds exactly the n/2 smallest values, so the lower median is the largest of them, and std::max_element finds it in one linear scan. Selecting again with a second nth_element call would also work, but it does more work than necessary.
Complexity and implementation
The C++ standard requires nth_element to be linear on average. It does not require linear time in the worst case. In practice:
- libstdc++ (GCC) uses introselect. It runs quickselect with a median-of-three pivot and tracks a depth limit of about 2·log₂(n). If the limit is exceeded, it switches to a heap-based selection, which bounds the worst case at O(n log n). Small subranges are finished with insertion sort.
- libc++ (Clang) and Microsoft's STL use their own quickselect variants with similar small-range cutoffs. Their worst-case behavior differs by version, so check the release notes if you rely on it.
None of these libraries uses median of medians as the main loop, for the reason covered in the median-of-medians chapter: its constant factors are too high for typical inputs.
Requirements and gotchas
Random-access iterators only. std::vector, std::array, std::deque, and raw pointers work. std::list and std::forward_list do not compile. Copy the data into a vector first.
The comparator must be a strict weak ordering. It must return true only when the first argument is strictly less than the second. Passing std::less_equal or a lambda written with <= violates this and is undefined behavior. The program may give wrong answers, loop forever, or read past the end of the range.
Floating-point NaN breaks the ordering. Every comparison involving NaN returns false, which also violates strict weak ordering. Remove NaNs before selecting, or use a comparator that orders them explicitly:
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
int main() {
const double nan = std::numeric_limits<double>::quiet_NaN();
std::vector<double> d{3.0, nan, 1.0, 2.0};
// Treat NaN as larger than every number, and equal to other NaNs.
auto nan_last = [](double a, double b) {
if (std::isnan(a)) return false;
if (std::isnan(b)) return true;
return a < b;
};
std::nth_element(d.begin(), d.begin() + 1, d.end(), nan_last);
std::cout << d[1] << '\n'; // 2
}nth == last does nothing. This is legal, and the range is left unchanged. Reading *nth afterward is out of bounds, so check that k < size() yourself, because the library does not.
You often want a different algorithm. If you need the top k elements in sorted order, std::partial_sort(first, first + k, last) gives exactly that in O(n log k). If you need only the set of the top k in any order, nth_element at position k - 1 (or k) is cheaper: once it returns, the first k elements are those values.
numpy.partition in Python
Signature and basic use
numpy.partition(a, kth, axis=-1, kind='introselect', order=None)np.partition returns a new array and leaves the input unchanged. The method ndarray.partition(kth, ...) does the same work in place and returns None. The only supported kind is 'introselect', so NumPy's worst case is bounded in the same way as libstdc++'s.
import numpy as np
a = np.array([9, 1, 8, 2, 7, 3])
k = 2
p = np.partition(a, k)
print(p[k]) # 3
print(sorted(p[:k]), sorted(p[k + 1:])) # [1, 2] [7, 8, 9]
print(a) # [9 1 8 2 7 3] (unchanged)
a.partition(k) # in place
print(a[k]) # 3Negative and multiple kth values
kth can be negative, and it counts from the end the same way slice indices do. np.partition(a, -1)[-1] is the maximum.
kth can also be a sequence. NumPy then guarantees that every listed position holds its sorted value, and that the elements between two listed positions fall between those values. This handles an even-length median in one call:
import numpy as np
x = np.array([7, 1, 5, 3, 9, 2])
n = len(x)
p = np.partition(x, [n // 2 - 1, n // 2])
print((p[n // 2 - 1] + p[n // 2]) / 2) # 4.0Internally NumPy selects the listed positions from largest to smallest and narrows the range each time, so asking for several positions costs much less than several separate calls.
Indices with argpartition
np.argpartition returns the indices that would partition the array, matching how np.argsort relates to np.sort. Use it when you need to know where the selected values came from, which is the usual case for "top k" problems such as ranking search results or picking the highest-scoring predictions.
import numpy as np
scores = np.array([0.2, 0.9, 0.4, 0.75, 0.1, 0.6])
k = 3
idx = np.argpartition(scores, -k)[-k:] # top-k indices, any order
idx = idx[np.argsort(scores[idx])[::-1]] # sort only those k
print(idx, scores[idx]) # [1 3 5] [0.9 0.75 0.6 ]This pattern costs O(n + k log k). A full np.argsort costs O(n log n). The difference matters when n is in the millions and k is small.
Axes, NaN, and structured arrays
By default NumPy partitions along the last axis, so each row of a 2-D array is handled on its own. Pass axis=None to flatten first.
import numpy as np
m = np.array([[5, 1, 4],
[3, 9, 2]])
print(np.partition(m, 1, axis=1)[:, 1]) # [4 3] per-row median
print(np.partition(m, 2, axis=None)[2]) # 3 over all six values
f = np.array([3.0, np.nan, 1.0, 2.0])
print(np.partition(f, 1)[1]) # 2.0
print(np.partition(f, -1)[-1]) # nanNaN is placed after every number, the same rule np.sort uses. That means a "maximum" taken from the end of a partitioned array can be NaN. Use np.nanmedian or filter with f[~np.isnan(f)] if NaNs mean missing data.
For structured arrays, the order argument names the field or fields to compare, as in np.sort.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Expecting the whole output to be sorted | Tests fail randomly or after a library upgrade | Check only `a[k]`, or sort the slices you care about |
| Using a one-based k | Off-by-one answer, e.g. 4th smallest instead of 3rd | Pass `k - 1` for "the k-th smallest" in everyday wording |
| `<=` comparator in C++ | Undefined behavior, crashes, wrong results | Use a strict `<` comparator |
| NaN in `double` data with default `<` in C++ | Undefined behavior | Filter NaNs or use an explicit NaN-aware comparator |
| Forgetting `ndarray.partition` returns `None` | `TypeError: 'NoneType' object is not subscriptable` | Use `np.partition(a, k)` for a copy, or index `a` after the in-place call |
| Taking top k from `argpartition` and assuming it is ranked | Results come out in arbitrary order | Sort the k selected indices by their values |
| Calling nth_element on `std::list` | Compile error about iterator category | Copy into `std::vector` |
| Out-of-range k | C++: undefined behavior. NumPy: `ValueError` | Validate `0 <= k < n` before the call in C++ |
Choosing the Right Routine
| Task | C++ | NumPy / Python | Cost |
|---|---|---|---|
| Single k-th element | `std::nth_element` | `np.partition` | O(n) average |
| Median | `nth_element` + `max_element` | `np.partition` with two kth, or `np.median` | O(n) average |
| Top k, sorted | `std::partial_sort` | `argpartition` + `argsort` on k | O(n log k) or O(n + k log k) |
| Top k from a stream | `std::priority_queue` | `heapq.nsmallest` / `nlargest` | O(n log k), O(k) memory |
| Many quantiles | `std::sort` | `np.sort` or `np.quantile` | O(n log n) |
np.median and np.percentile already use partitioning internally, so prefer them for those specific statistics. Reach for np.partition directly when you need the indices, several custom positions, or the rearranged data itself.
Exercise
You run std::nth_element(v.begin(), v.begin() + 3, v.end()) on std::vector<int> v{4, 8, 1, 6, 3, 9, 2}. Which values are guaranteed to be in v[0..2], what is v[3], and what can you say about the order of v[4..6]?
Show answer
Sorted, v is {1, 2, 3, 4, 6, 8, 9}. v[3] is 4. v[0..2] contain exactly {1, 2, 3} in some unspecified order, and v[4..6] contain exactly {6, 8, 9} in some unspecified order. The library makes no guarantee about the order inside either group.
Exercise
Write NumPy code that returns the indices of the 5 smallest values in a 1-D array d (length at least 5), ordered from smallest to largest value, without sorting the whole array.
Show answer
idx = np.argpartition(d, 4)[:5] followed by idx = idx[np.argsort(d[idx])]. argpartition at kth=4 places the five smallest values at positions 0 to 4 in arbitrary order, and argsort then ranks only those five. The total cost is O(n + 5 log 5).
Exercise
A colleague sorts a vector of doubles that may contain NaN with std::nth_element(v.begin(), v.begin() + k, v.end(), [](double a, double b){ return a <= b; });. Name the two separate problems with this call.
Show answer
First, <= is not a strict weak ordering because it returns true for equal elements, which is undefined behavior. Second, even with <, NaN values make every comparison false, which also breaks strict weak ordering. Use a strict comparator that explicitly orders NaN, or remove NaNs before the call.
Exercise
Why does np.partition(x, [n // 2 - 1, n // 2]) cost less than calling np.partition twice with each index?
Show answer
With several kth values, NumPy selects the largest position first and then searches for the next one only inside the already-narrowed left range. The second selection works on a smaller subarray and reuses the first partition. Two separate calls would each start over on the full array.