LearnWithKiriti

Quick Sort

Medium GitHub ↗
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Optimal: Quick Sort

Revision notes

Quick Sort

Video: “Quick Sort: lucky pivot or O(n²)?” on LearnWithKiriti (Kodee).

Sort an array in place by partitioning around a pivot and sorting each side. Example: [7, 2, 8, 1, 5] -> [1, 2, 5, 7, 8]

Folder Approach Time Extra space
Optimal-QuickSort/ Quick sort: Partition around the last number (pivot): scan moves left to right, and everything ≤ pivot is swapped behind the wall. The pivot lands at the wall, then sort each side. O(n log n) on average, O(n²) worst O(log n) extra (recursion)

Rebuild it from the name

Quick: partition around a pivot, then sort each side. Take the last number as the pivot. scan walks from low; every number <= pivot is swapped behind the wall. Finally the pivot swaps onto the wall: everything left is smaller, everything right is bigger, and the pivot is in its final place. Repeat on each side. A lucky pivot halves the work (O(n log n)); an unlucky one on sorted input peels off one number per level (O(n²)).

See Optimal-QuickSort/pseudocode.md. Every program runs Example 1 and prints the answer (the part under “Run it locally”); the same code is in the practice panel’s Start menu on learnwithkiriti.com, where Shelf Bot can act it out.

optimal

Optimal: Quick Sort

Quick sort (last number as pivot)

Partition around the last number (pivot): scan moves left to right, and everything ≤ pivot is swapped behind the wall. The pivot lands at the wall, then sort each side.

quickSortHelper(low, high):
    if low >= high: return
    pivotSpot = partition(low, high)
    quickSortHelper(low, pivotSpot - 1)
    quickSortHelper(pivotSpot + 1, high)

partition(low, high):
    pivot = nums[high]
    wall = low
    for scan from low to high - 1:
        if nums[scan] <= pivot:
            swap nums[wall] and nums[scan]
            wall = wall + 1
    swap nums[wall] and nums[high]
    return wall

Dry run on Example 1:

partition([7, 2, 8, 1, 5]), pivot = 5:

scan value <= 5? wall after array
0 7 no 0 [7, 2, 8, 1, 5]
1 2 yes 1 [2, 7, 8, 1, 5]
2 8 no 1 [2, 7, 8, 1, 5]
3 1 yes 2 [2, 1, 8, 7, 5]
end pivot to wall [2, 1, 5, 7, 8]

5 is final; sort [2, 1] and [7, 8].

Average O(n log n); worst O(n²) when the pivot is always the smallest or biggest (sorted input with a last-number pivot). Extra space: the recursion, O(log n) on average. Not stable. A random pivot makes the worst case very unlikely.

QuickSortOptimal.java
class Solution {
    public void quickSort(int[] nums) {
        quickSortHelper(nums, 0, nums.length - 1);
    }

    private void quickSortHelper(int[] nums, int low, int high) {
        // one number is already sorted
        if (low >= high) {
            return;
        }
        int pivotSpot = partition(nums, low, high);
        quickSortHelper(nums, low, pivotSpot - 1);
        quickSortHelper(nums, pivotSpot + 1, high);
    }

    private int partition(int[] nums, int low, int high) {
        int pivot = nums[high];
        // everything left of wall is <= pivot
        int wall = low;
        for (int scan = low; scan < high; scan++) {
            if (nums[scan] <= pivot) {
                swap(nums, wall, scan);
                wall++;
            }
        }
        swap(nums, wall, high);
        return wall;
    }

    private void swap(int[] nums, int left, int right) {
        int held = nums[left];
        nums[left] = nums[right];
        nums[right] = held;
    }
}