Typorithm · medium

Quick Select

▷ Interactive algorithm labquick-selectdivide-and-conquerpartitionkth-elementone-side
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Quick Select

0%

Divide & Conquer

Partition like Quick Sort, but only recurse into the side holding index k — average O(n).

Quick Select finds the kth smallest element without fully sorting the array.

Each partition places the pivot at its final index and splits values around it.

Unlike Quick Sort, you only continue into the half that contains k, halving the work on average.

Preparing algorithm lab…
01

Partition places the pivot exactly.

02

Recurse into one side only.

03

Average O(n), worst O(n^2).

function quickSelect(nums, k) {
  function partition(left, right) {
    const pivot = nums[right];
    let i = left;

    for (let j = left; j < right; j += 1) {
      if (nums[j] < pivot) {
        [nums[i], nums[j]] = [nums[j], nums[i]];
        i += 1;
      }
    }

    [nums[i], nums[right]] = [nums[right], nums[i]];
    return i;
  }

  let left = 0;
  let right = nums.length - 1;

  while (left <= right) {
    const pivotIndex = partition(left, right);
    if (pivotIndex === k) return nums[pivotIndex];
    if (pivotIndex < k) left = pivotIndex + 1;
    else right = pivotIndex - 1;
  }

  return -1;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Pick pivot

Use the last value as the pivot for this partition.

const pivot = nums[right]

2. Move smaller left

Swap values smaller than the pivot to the left region.

[nums[i], nums[j]] = [nums[j], nums[i]]

3. Place pivot

Drop the pivot into its final sorted position at index i.

[nums[i], nums[right]] = [nums[right], nums[i]]

4. Found k

When the pivot lands at k, it is the kth smallest.

if (pivotIndex === k) return nums[pivotIndex]

5. Keep one side

Recurse into only the half that contains k, not both.

if (pivotIndex < k) left = pivotIndex + 1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Quick Select: Visual Walkthrough & Practice · Typorithm | ApplyDjinn