Quickselect
25 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Quickselect finds the kth smallest or largest element in average O(n) time using partitioning.
The selection problem and the brute force
Finding the kth smallest value does not need a full sort. The simplest answer sorts a copy and reads one slot; the program below does that for five salaries.
Example 1 · Brute force: sort a copy, then read slot k (O(n log n) time, O(n) space)
import java.util.Arrays;
public class QuickselectSortBrute { public static int kthSmallest(int[] salaries, int k) { int[] sorted = salaries.clone(); Arrays.sort(sorted); return sorted[k - 1]; }
public static void main(String[] args) { int[] salaries = {52000, 38000, 71000, 45000, 60000}; System.out.println("2nd smallest salary: " + kthSmallest(salaries, 2)); }}2nd smallest salary: 45000
What this code does
Arrays.sortputs all five salaries in order, although only the value at one slot is needed.- Sorting does about n log n comparisons, and most of them order values far from rank k.
- The clone keeps the original array unchanged, at the price of O(n) extra memory.
The selection problem asks for the kth smallest or largest element without fully sorting. For example, finding the median salary requires locating the middle element.
Sorting takes O(n log n) time and reorganises all elements unnecessarily. We only care about the single value that belongs at index k. Sorting 10 million elements requires over 200 million comparisons, and most of them sort elements far away from rank k.
Better: a heap of size k
A min-heap of size k can track the k largest values while the array is read once. The program below finds the second largest salary this way.
Example 2 · Better: min-heap of size k (O(n log k) time, O(k) space)
import java.util.PriorityQueue;
public class QuickselectHeap { public static int kthLargest(int[] salaries, int k) { PriorityQueue<Integer> heap = new PriorityQueue<>(); for (int x : salaries) { heap.offer(x); if (heap.size() > k) { heap.poll(); } } return heap.peek(); }
public static void main(String[] args) { int[] salaries = {52000, 38000, 71000, 45000, 60000}; System.out.println("2nd largest salary: " + kthLargest(salaries, 2)); }}2nd largest salary: 60000
What this code does
- The heap never holds more than k values, so each offer or poll costs O(log k) instead of sorting everything.
- After the loop the smallest of the k largest values, which is the kth largest, sits at the top.
- This is faster than sorting when k is small, and it works on a stream.
The heap-based approach keeps a heap of size k. To find the kth largest, keep a min-heap of size k: offer each element and poll when the size exceeds k. The root is then the kth largest.
It takes O(n log k) time and O(k) extra memory, and it works on data that arrives as an endless stream because it never stores everything.
Optimal: quickselect step by step
Quickselect partitions like quick sort but keeps only the side that contains rank k. The examples find the kth smallest, the kth largest and the median.
Example 3 · Optimal: kth smallest with quickselect (O(n) average time, O(1) extra space)
public class QuickselectDemo { public static int quickselect(int[] arr, int low, int high, int k) { if (low == high) return arr[low]; int pivotIndex = partition(arr, low, high); if (pivotIndex == k) { return arr[pivotIndex]; } else if (pivotIndex > k) { return quickselect(arr, low, pivotIndex - 1, k); } else { return quickselect(arr, pivotIndex + 1, high, k); } }
private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } int temp = arr[i]; arr[i] = arr[high]; arr[high] = temp; return i; }
public static void main(String[] args) { int[] arr = {7, 10, 4, 3, 20, 15}; int k = 2; // 3rd smallest (0-indexed: 2) int result = quickselect(arr, 0, arr.length - 1, k); System.out.println("Element at rank " + k + ": " + result); }}Element at rank 2: 7
What this code does
- Only the side that contains rank k is searched, so the work is n + n/2 + n/4 + ... which adds up to about 2n.
- Base case checks if the search range contains only one element.
- Partition places the chosen pivot at its sorted position.
- Compares pivot index with target index k.
Example 4 · Optimal: kth largest with iterative quickselect (O(n) average time, O(1) extra space)
public class KthLargestIterativeDemo { public static int findKthLargest(int[] nums, int k) { int target = nums.length - k; int low = 0, high = nums.length - 1; while (low < high) { int p = partition(nums, low, high); if (p == target) { return nums[p]; } else if (p < target) { low = p + 1; } else { high = p - 1; } } return nums[low]; }
private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } int temp = arr[i]; arr[i] = arr[high]; arr[high] = temp; return i; }
public static void main(String[] args) { int[] nums = {3, 2, 1, 5, 6, 4}; int k = 2; System.out.println("2nd largest: " + findKthLargest(nums, k)); }}2nd largest: 5
What this code does
- Converts kth largest query into index n - k for ascending order.
- Uses an iterative loop instead of recursion to save stack frames.
- Updates low boundary when pivot lands to the left of target.
Example 5 · Optimal: median with randomised quickselect (O(n) expected time, O(1) extra space)
import java.util.Random;
public class MedianFindingDemo { private static final Random rng = new Random(42);
public static int findMedian(int[] nums) { int target = nums.length / 2; return quickselect(nums, 0, nums.length - 1, target); }
private static int quickselect(int[] arr, int low, int high, int k) { if (low == high) return arr[low]; int pivotIdx = low + rng.nextInt(high - low + 1); int temp = arr[pivotIdx]; arr[pivotIdx] = arr[high]; arr[high] = temp;
int p = partition(arr, low, high); if (p == k) return arr[p]; if (p > k) return quickselect(arr, low, p - 1, k); return quickselect(arr, p + 1, high, k); }
private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; i++; } } int t = arr[i]; arr[i] = arr[high]; arr[high] = t; return i; }
public static void main(String[] args) { int[] nums = {9, 1, 0, 2, 3, 4, 6, 8, 7}; System.out.println("Median value: " + findMedian(nums)); }}Median value: 4
What this code does
- Computes middle index n / 2 as the target for median search.
- Swaps a randomly chosen pivot to the end before partitioning.
- Random pivot selection guards against worst-case degradation.
Quickselect inspects the pivot index p after partitioning. If p equals target index k, the pivot is our answer. If p is greater than k, the kth element must be in the left partition. If p is less than k, the kth element must be in the right partition. Unlike quicksort, quickselect never recurses on both partitions. It discards one half of the array at each step. The problem size shrinks from n to n/2, then n/4, down to 1. The sum n + n/2 + n/4 + ... converges to at most 2n comparisons. Consider tracing 2nd smallest (index 1) on [7, 10, 4, 3, 20, 15]: Choose pivot 15. Partitioning yields [7, 10, 4, 3], 15, [20] with pivot at index 4. Since target index 1 is less than 4, recurse only on left subarray [7, 10, 4, 3]. Next partition [7, 10, 4, 3] with pivot 3: 3 lands at index 0. Since 1 is greater than 0, recurse on [7, 10, 4]. Pivot 4 lands at index 1, matching target index 1 and returning value 4.
Quickselect runs in average O(n) time and needs O(1) extra memory, but its worst case degrades to O(n²) if partitions are unbalanced. A random pivot makes that worst case very unlikely. It also changes the original array while partitioning. Choose a heap when data arrives continuously as a stream. Choose quickselect when the whole dataset fits in memory and may be changed, because it has the best raw speed for batch selection.
Predict the output
Which side next?
Read each snippet and pick what it prints.
Round 1 of 2
Next step
Check your understanding
10 quick questions