1. Pick pivot
Use the last value as the pivot for this partition.
const pivot = nums[right]Typorithm · medium
Step 1 of 8 · intro card
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.
Partition places the pivot exactly.
Recurse into one side only.
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;
}Connect each part of the code to the concept before you type.
Use the last value as the pivot for this partition.
const pivot = nums[right]Swap values smaller than the pivot to the left region.
[nums[i], nums[j]] = [nums[j], nums[i]]Drop the pivot into its final sorted position at index i.
[nums[i], nums[right]] = [nums[right], nums[i]]When the pivot lands at k, it is the kth smallest.
if (pivotIndex === k) return nums[pivotIndex]Recurse into only the half that contains k, not both.
if (pivotIndex < k) left = pivotIndex + 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputArray [5,1,4,2,8] · zero-based k = 2
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state