Quick sort (recursion)
Medium TimeO(n log n) average, O(n²) worst SpaceO(n)
Given an array arr of numbers, return them in ascending order, sorted by splitting the rest around a pivot rather than by merging halves. Duplicates are all kept, and an array of 0 or 1 values is already sorted.
Examples
Example 1
- Input
- arr = [5, 2, 8, 1, 9, 3]
- Output
- The same six values, ascending.
[1,2,3,5,8,9]
Example 2
- Input
- arr = [2, 2, 2]
- Output
- Three equal values, and all three come back.
[2,2,2]
The Code
function quickSort(arr) {
if (arr.length <= 1) return arr;
const [pivot, ...rest] = arr;
const left = rest.filter((x) => x < pivot);
const right = rest.filter((x) => x >= pivot);
return [...quickSort(left), pivot, ...quickSort(right)];
}
quickSort([5, 2, 8, 1, 9, 3]);Done
More like this
All sorting examples (8) →- Merge sort Divide and conquer — split in half, sort, then merge.
- Bubble sort Repeatedly swap adjacent out-of-order pairs until sorted.
- Insertion sort Grow a sorted prefix, inserting each new item into place.
- Selection sort Find the smallest remaining element and swap it into place.
- Counting sort No comparisons — tally each value, then read the tallies back out.
- Heap sort Build a max-heap, then repeatedly move the root to the back.