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.

JavascriptData Integrity

Code

javascriptsnippet
26 lines
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.length short-circuits the flow with an early throw when 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

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.