When the pivot always divides the array into nearly equal halves, quick sort achieves its best performance.
For random arrays, quick sort is very efficient with O(n log n) time complexity.
When the pivot is always the smallest or largest element (e.g., in already sorted arrays), quick sort degrades to O(n²) performance.
function quickSort(arr, low = 0, high = arr.length - 1) {
if (low < high) {
// Find pivot element such that
// elements smaller than pivot are on the left
// elements greater than pivot are on the right
const pivotIndex = partition(arr, low, high);
// Recursively sort elements before and after pivot
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
return arr;
}
function partition(arr, low, high) {
// Choose rightmost element as pivot
const pivot = arr[high];
let i = low - 1;
// Compare each element with pivot
for (let j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// Place pivot in its final position
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}