75

Pick a pivot, partition the array so smaller elements are on the left and larger on the right, then sort both sides recursively. Average O(n log n), in-place. Worst case O(n²) when the pivot is always the smallest/largest (e.g. already sorted input with last-element pivot); a random pivot avoids it.

After one partition the pivot is at its final index

After one partition the pivot is at its final index

C++ 16 lines
int partition(vector<int> &a, int low, int high) {   // Lomuto
    int pivot = a[high];
    int i = low - 1;
    for (int j = low; j < high; j++)
        if (a[j] < pivot) swap(a[++i], a[j]);
    swap(a[i + 1], a[high]);
    return i + 1;
}

void quickSort(vector<int> &a, int low, int high) {
    if (low < high) {
        int p = partition(a, low, high);
        quickSort(a, low, p - 1);
        quickSort(a, p + 1, high);
    }
}

Q & A

  1. Merge sort vs quick sort?
    Merge sort: always O(n log n), stable, needs O(n) extra memory, good for linked lists and external sorting. Quick sort: in-place and usually faster in practice, but O(n²) in the worst case and not stable.