← Back

Quick Sort

divide-and-conquerin-placeunstable
Press play to start
1function quickSort(arr: number[], lo = 0, hi = arr.length - 1): number[] {
2 if (lo < hi) {
3 const p = partition(arr, lo, hi)
4 quickSort(arr, lo, p - 1)
5 quickSort(arr, p + 1, hi)
6 }
7 return arr
8}
9function partition(arr: number[], lo: number, hi: number): number {
10 const pivot = arr[hi]
11 let i = lo - 1
12 for (let j = lo; j < hi; j++) {
13 if (arr[j] <= pivot) {
14 [arr[++i], arr[j]] = [arr[j], arr[i + 1]]
15 }
16 }
17 [arr[i + 1], arr[hi]] = [arr[hi], arr[i + 1]]
18 return i + 1
19}
Step 1/0
Custom array:

Complexity

Best:O(n log n)
Average:O(n log n)
Worst:O(n²)
Space:O(log n)

Description

Selects a pivot element, partitions the array into elements less than and greater than the pivot, then recursively sorts each partition.

When to use

Average O(n log n) with small constant factor. Typically fastest in practice for in-memory sorting. Widely used in system libraries.