Quickselect for the Kth Largest Element
Find the kth largest element in average linear time with quickselect, avoiding the cost of fully sorting when only one rank is needed.
Code
export function kthLargest(items, k) {
if (k < 1 || k > items.length) throw new RangeError("k out of range");
const target = items.length - k;
const data = items.slice();
let left = 0;
let right = data.length - 1;
while (true) {
const pivotIndex = partition(data, left, right);
if (pivotIndex === target) return data[pivotIndex];
if (pivotIndex < target) left = pivotIndex + 1;
else right = pivotIndex - 1;
}
}
function partition(data, left, right) {
const pivot = data[right];
let store = left;
for (let i = left; i < right; i++) {
if (data[i] < pivot) {
[data[i], data[store]] = [data[store], data[i]];
store++;
}
}
[data[right], data[store]] = [data[store], data[right]];
return store;
}How the snippet works
Quickselect for the Kth Largest Element reduces to the functions kthLargest and partition.
The nesting pairs while (true) with for (let i = left; i < right; i++) — the inner runs once per outer step. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
What to watch for
- The guard
k < 1 || k > items.lengthshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Entry signature: export function kthLargest(items, k)
Import kthLargest from the file and call it — the rest of the code is implementation detail.
Statements that matter
if (k < 1 || k > items.length) throw new RangeError("k out of range");
if (pivotIndex === target) return data[pivotIndex];
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What happens on invalid input?
- It throws `RangeError` before any real work runs, via the guard `k < 1 || k > items.length` — handle it at the call site or let it propagate deliberately.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `kthLargest`, `partition` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.