Sub topic 11
Using std::nth_element and numpy.partition
You have now built quickselect by hand, along with three-way partitioning and the introselect hybrid. In production code you will rarely write your own. C++ and NumPy both ship selection routines built on these ideas. This chapter assumes you know basic C++ (vectors, iterators, compiling a single file) and basic NumPy arrays, and that you understand the partition invariant from earlier chapters.
What the library routines promise
Both functions solve the same problem. After the call, the element at position k is the value that would be there if the range were sorted. Nothing before it is larger, and nothing after it is smaller. Neither side is sorted internally.
| Feature | `std::nth_element` | `numpy.partition` |
|---|---|---|
| Modifies input | Yes, in place | No, returns a copy (use `ndarray.partition` for in place) |
| Algorithm | Introselect in common implementations | Introselect by default (`kind="introselect"`) |
| Average time | Linear | Linear |
| Multiple `k` values | No, one call per position | Yes, pass a sequence of indices |
| Custom ordering | Comparator argument | No comparator, numeric ordering only |
| Index variant | None built in | `numpy.argpartition` |
std::nth_element in C++
The function takes three iterators: the start of the range, the position you want filled correctly, and the end.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
int main() {
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 << v[k] << '\n'; // prints 3
}To find the k-th largest, pass a comparator that reverses the order. The same idea works with lambdas for structs, for example to select by one field.
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{9, 1, 8, 2, 7, 3};
std::size_t k = 1; // 0-based: second largest
std::nth_element(v.begin(), v.begin() + k, v.end(), std::greater<int>());
std::cout << v[k] << '\n'; // prints 8
}Common errors with nth_element
- Expecting a sorted prefix. After the call,
v[0..k-1]holds the k smallest values in no particular order. If you need them sorted, callstd::partial_sortinstead, or sort the prefix afterward. - Forgetting it mutates. If the caller still needs the original order, copy the vector first.
- Passing
end()as the nth iterator. The call is then legal but does nothing useful. Check thatk < v.size()yourself, because the function has noIndexErrorequivalent. - Using an inconsistent comparator. The comparator must be a strict weak ordering. Using
<=breaks the algorithm's assumptions and can produce wrong results.
numpy.partition in Python
numpy.partition returns a new array with index kth in its sorted position.
import numpy as np
a = np.array([9, 1, 8, 2, 7, 3])
k = 2
print(np.partition(a, k)[k]) # 3You can pass several indices at once. NumPy puts every listed position in its sorted place in a single call, which is handy for quartiles or for a median of an even-length array.
import numpy as np
a = np.array([9, 1, 8, 2, 7, 3])
n = len(a)
mid = [n // 2 - 1, n // 2]
p = np.partition(a, mid)
print((p[mid[0]] + p[mid[1]]) / 2) # 5.0, the median of 1 2 3 7 8 9Negative indices count from the end, so np.partition(a, -1)[-1] is the maximum. The axis argument partitions each row or column independently, which saves you a Python loop over a 2-D array.
Top-k with argpartition
numpy.argpartition returns indices instead of values. This is the standard way to get the top-k items, such as the highest-scoring predictions, without sorting the whole array.
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 3, unordered
idx = idx[np.argsort(scores[idx])[::-1]] # sort only those 3
print(idx.tolist(), scores[idx].tolist()) # [1, 3, 5] [0.9, 0.75, 0.6]The first line costs linear time. The second sorts only k elements, so the total is O(n + k log k) instead of O(n log n).
Choosing the right call
For plain Python lists of modest size, heapq.nsmallest(k, items) or sorted(items)[k] is often fast enough. Switch to NumPy or C++ when profiling shows that selection matters.
Exercise
After running std::nth_element(v.begin(), v.begin() + 3, v.end()) on a vector of 10 distinct ints, which statements are guaranteed: (a) v[3] is the 4th smallest value, (b) v[0..2] are sorted, (c) every element in v[4..9] is at least v[3]?
Show answer
(a) and (c) are guaranteed. (b) is not: the first three elements are the three smallest values, but they can be in any order.
Exercise
You have a NumPy array of 10 million floats and need the indices of the 100 largest, ordered from largest to smallest. Write the two lines that do this without sorting the full array.
Show answer
idx = np.argpartition(a, -100)[-100:] followed by idx = idx[np.argsort(a[idx])[::-1]]. The first line runs in linear time and the second sorts only 100 elements.