Quickselect and finding the k-th element

You rarely need the whole array sorted — selecting the k-th takes O(n) on average.

"Find the k-th smallest element" does not require sorting. Sorting orders all n elements when you asked about one, and that costs O(n log n) for information you throw away.

Quickselect

Quicksort's partition step, recursing into only the side that can contain the answer:

function quickSelect(a, k) {          // k is zero-based
  let lo = 0;
  let hi = a.length - 1;

  while (lo <= hi) {
    const p = partition(a, lo, hi);   // same partition as quicksort

    if (p === k) return a[p];
    if (p < k) lo = p + 1;            // answer is to the right
    else hi = p - 1;                  // answer is to the left
  }

  throw new RangeError('k is out of range');
}

Each partition is linear and the remaining range halves on average, so the work is n + n/2 + n/4 + … = O(n) on average. The worst case is O(n²) with unlucky pivots; a random pivot makes that vanishingly unlikely, and median-of-medians guarantees O(n) at a constant factor nobody pays in practice.

It sorts nothing and it mutates the input — mention both if the caller cares.

The heap alternative

For "top k of a large stream", a heap of size k is usually the better tool:

// Keep the k largest: a min-heap of size k, evicting the smallest.
// O(n log k) time, O(k) space — and it never needs the whole input in memory.
Approach Time Space Needs all data at once
Sort, take k O(n log n) O(1)–O(n) Yes
Quickselect O(n) average O(1) Yes
Heap of size k O(n log k) O(k) No

Choose quickselect when the array is in memory and k is arbitrary; choose the heap when data streams, when k is small relative to n, or when the input must not be mutated.

Where it shows up

The median is quickselect at k = n/2. "k closest points to the origin", "k-th largest in an array", and percentile calculations over fixed datasets are all the same call. Naming both approaches and their trade — average O(n) versus streaming O(n log k) — is a complete answer to the interview version.