In this article, we’ll dive into Quick Sort, a high-performance, divide-and-conquer sorting algorithm that’s widely used in real-world applications and coding interviews.
Quick Sort is a divide and conquer algorithm that picks a pivot element from the array and partitions the other elements into two sub-arrays:
Then, it recursively sorts the sub-arrays and merges them together.
Let’s say we want to sort this array:
[8, 4, 7, 3, 1, 5, 2]
2
).< 2
→ [1]
>= 2
→ [8, 4, 7, 3, 5]
[1]
and [8, 4, 7, 3, 5]
[1] + [2] + quickSort([8, 4, 7, 3, 5])
Repeat this process until the whole array is sorted.
Here’s a clean and readable version using recursion and array methods:
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)];}
const unsorted = [8, 4, 7, 3, 1, 5, 2];const sorted = quickSort(unsorted);console.log(sorted); // Output: [1, 2, 3, 4, 5, 7, 8]
Case | Time Complexity |
---|---|
Best Case | O(n log n) |
Average Case | O(n log n) |
Worst Case | O(n²) (if poorly implemented) |
The version above uses extra space for left and right arrays. Here’s an in-place version that modifies the original array:
function quickSortInPlace(arr, left = 0, right = arr.length - 1) {if (left < right) {const pivotIndex = partition(arr, left, right);quickSortInPlace(arr, left, pivotIndex - 1);quickSortInPlace(arr, pivotIndex + 1, right);}return arr;}function partition(arr, left, right) {const pivot = arr[right];let i = left;for (let j = left; j < right; j++) {if (arr[j] < pivot) {[arr[i], arr[j]] = [arr[j], arr[i]];i++;}}[arr[i], arr[right]] = [arr[right], arr[i]];return i;}
Quick Sort is one of the fastest and most efficient sorting algorithms when implemented correctly. It’s widely used in the real world, often even under the hood in language libraries like JavaScript’s Array.prototype.sort()
(in most modern engines).
Knowing how it works—and how to implement both recursive and in-place versions—gives you a powerful tool in your algorithm toolbox.
Quick Links
Legal Stuff
Social Media