1. Base case
A length 0 or 1 array is already sorted, so recursion stops.
if (arr.length <= 1) return arrTyporithm · medium
Step 1 of 8 · intro card
Sorting Algorithms
Quick Sort partitions around a pivot, then recursively sorts the values below and above that pivot.
The base case returns arrays of length 0 or 1 because they are already sorted.
This implementation chooses the last value as the pivot for readability.
Every other value is partitioned into left or right based on whether it is smaller than the pivot.
The final result is sorted left partition, pivot, then sorted right partition.
Average time is O(n log n), but consistently bad pivots can degrade to O(n^2).
Pick a pivot.
Partition values by comparing with the pivot.
Recursively sort both partitions.
Average O(n log n), worst O(n^2).
This readable version uses extra arrays.
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[arr.length - 1];
const left = [];
const right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}Connect each part of the code to the concept before you type.
A length 0 or 1 array is already sorted, so recursion stops.
if (arr.length <= 1) return arrThis version chooses the final value as the pivot.
const pivot = arr[arr.length - 1]Values smaller than the pivot are collected on the left.
const left = []Values greater than or equal to the pivot are collected on the right.
const right = []Scan every value except the pivot itself.
for (let i = 0; i < arr.length - 1; i++)Each value goes left or right based on the pivot comparison.
arr[i] < pivotSmaller values go into the left recursive problem.
left.push(arr[i])Sort the partitions recursively and place the pivot between them.
return [...quickSort(left), pivot, ...quickSort(right)]Read 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
Input[5,1,4,2,8]
In-place partitioning with one swap temporary; recursive stack averages O(log n), but may grow to O(n). 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