Sub topic 3
Handling Duplicates, Alternatives, and Library Support
This chapter assumes you know the Lomuto partition and the in-place quickselect loop from the previous chapter, as well as Big-O notation.
Three-Way Partitioning for Duplicate Keys
Lomuto partitioning sends every element equal to the pivot to one side. When most of the array holds the same value, each pass removes only the pivot itself, and the run time becomes O(n^2). Three-way partitioning, also called the Dutch national flag scheme, fixes this. It splits the range into three groups: less than the pivot, equal to it, and greater than it. If k lands in the equal group, the search is done.
import random
def quickselect3(a, k):
"""In-place quickselect with three-way partitioning (0-based k)."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
return a[k]
print(quickselect3([5, 5, 5, 1, 5, 9, 5], 3)) # 5Quickselect Versus Sorting and Heaps
| Method | Time | Extra space | Best when |
|---|---|---|---|
| Sort, then index | O(n log n) | O(1) to O(n) | You need many order statistics |
| Heap of size k | O(n log k) | O(k) | Data is streamed or k is small |
| Quickselect | Expected O(n) | O(1) | You need a single k-th element from an array you can modify |
Median of Medians: Guaranteed Linear Time
Median of medians splits the input into groups of five and takes the median of each group. It then recursively selects the median of those medians and uses that value as the pivot. This pivot is guaranteed to be larger than about 30% of the elements and smaller than about 30%, so every step discards a fixed fraction of the input. That guarantee gives worst-case O(n) time. The constant factors are large, so randomized quickselect is usually faster in practice.
Introselect: Speed With a Safety Net
Introselect runs ordinary quickselect and counts how much work it has done. If the range is not shrinking quickly enough, it switches to a pivot method with a guarantee, such as median of medians, or in some implementations to heapselect. The common case stays fast and the worst case stays bounded.
Library Routines
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{9, 1, 8, 2, 7, 3};
std::nth_element(v.begin(), v.begin() + 2, v.end());
std::cout << v[2] << '\n'; // 3
}import numpy as np
a = np.array([9, 1, 8, 2, 7, 3])
print(np.partition(a, 2)[2]) # 3Exercise
You need the median of an array of one million integers that are almost all equal to 0. Why can Lomuto-based quickselect be slow here, and what change fixes it?
Show answer
With Lomuto, every element equal to the pivot goes to the same side, so each pass removes very little and the run time approaches O(n^2). Three-way partitioning groups all the zeros together. The search then ends as soon as k falls inside that equal group, which takes about one pass.