Quickselect — kth largest
Medium TimeO(n) average SpaceO(log n) stack
Given an unsorted array arr and a number k, return the kth largest value — for [3, 2, 1, 5, 6, 4] and k = 2 that is 5. k counts from 1, so k = 1 asks for the largest; duplicates count as separate positions, and k is never larger than the array.
Examples
Example 1
- Input
- arr = [3, 2, 1, 5, 6, 4]k = 2
- Output
- 6 is the largest and 5 is the next, so the 2nd largest is
55.
Example 2
- Input
- arr = [3, 2, 1, 5, 6, 4]k = 1
- Output
6k = 1asks for the largest value in the array, which is 6.
The Code
function quickselect(arr, k) {
const target = arr.length - k;
function select(low, high) {
const pivot = arr[high];
let store = low;
for (let i = low; i < high; i++) {
if (arr[i] < pivot) {
const temp = arr[i];
arr[i] = arr[store];
arr[store] = temp;
store++;
}
}
const temp = arr[high];
arr[high] = arr[store];
arr[store] = temp;
if (store === target) return arr[store];
if (store < target) return select(store + 1, high);
return select(low, store - 1);
}
return select(0, arr.length - 1);
}
quickselect([3, 2, 1, 5, 6, 4], 2);Done
More like this
All sorting examples (8) →- Merge sort Divide and conquer — split in half, sort, then merge.
- Quick sort Pick a pivot, partition around it, recurse on each side.
- Bubble sort Repeatedly swap adjacent out-of-order pairs until sorted.
- Insertion sort Grow a sorted prefix, inserting each new item into place.
- Selection sort Find the smallest remaining element and swap it into place.
- Counting sort No comparisons — tally each value, then read the tallies back out.