Partition Sort: Quick Sort

Quick Sort is a highly efficient, comparison-based sorting algorithm that uses a Divide and Conquer strategy. While it has a worse theoretical worst-case performance than Merge Sort, in practice it is often faster due to its low constant factors and superior cache locality.


1. The Core Mechanism: Partitioning

The heart of Quick Sort is the "Partition" operation.

  1. Pick a Pivot: Choose an element from the array (e.g., the last element).
  2. Partition: Reorder the array so that all elements smaller than the pivot are on the left, and all elements larger are on the right.
  3. Recurse: Apply the same logic to the left and right sub-arrays independently.

2. Complexity Analysis

Scenario Time Complexity Space Complexity
Best Case O(N log N) O(log N)
Average Case O(N log N) O(log N)
Worst Case O(N²) O(log N)

3. Implementation (Lomuto Partition)

function quickSort(arr, low = 0, high = arr.length - 1) {
    if (low < high) {
        let pIdx = partition(arr, low, high);
        quickSort(arr, low, pIdx - 1);
        quickSort(arr, pIdx + 1, high);
    }
    return arr;
}

function partition(arr, low, high) {
    let pivot = arr[high];
    let i = low - 1;

    for (let j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            [arr[i], arr[j]] = [arr[j], arr[i]];
        }
    }
    [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
    return i + 1;
}

4. Interview Pro-Tips: Optimizing the Pivot

A common follow-up question: "How do you prevent the O(N²) worst case?"


Technical Summary

  1. Partition: The single most important operation.
  2. Pivot: The variable that determines the efficiency of the split.
  3. In-Place: Superior memory efficiency compared to Merge Sort.
  4. Unstable: Choosing efficiency over stability.