JavaScript Algorithms: Quicksort
By Flavio Copes
Learn how quicksort works in JavaScript by choosing a pivot, partitioning the remaining values, and recursively sorting both sides without losing duplicates.
Quicksort is a sorting algorithm.
It picks one value called the pivot, splits the other values around it, and recursively sorts both groups.
Here is a small non-mutating implementation:
function quickSort(items) {
if (items.length < 2) {
return [...items]
}
const [pivot, ...rest] = items
const smallerOrEqual = rest.filter(item => item <= pivot)
const bigger = rest.filter(item => item > pivot)
return [
...quickSort(smallerOrEqual),
pivot,
...quickSort(bigger)
]
}
Removing the pivot from rest is important. Values equal to the pivot go into smallerOrEqual, so duplicates are not lost.
The function returns a new array:
const numbers = [1, 6, 3, 4, 5, 1, 0, 4, 8]
console.log(quickSort(numbers))
//[0, 1, 1, 3, 4, 4, 5, 6, 8]
console.log(numbers)
//[1, 6, 3, 4, 5, 1, 0, 4, 8]
Quicksort runs in O(n log n) time on average. Its worst case is O(n²), which can happen when the pivot repeatedly produces a very uneven split.
This example always uses the first item as the pivot because it keeps the code clear. Real implementations use better pivot strategies and often sort in place to avoid creating all these temporary arrays.
For application code, use the built-in sorting methods unless you are learning algorithms:
const sorted = numbers.toSorted((a, b) => a - b)
toSorted() returns a new array. The older sort() method changes the original array.