Skip to content

Quick Sort

Efficient divide-and-conquer sorting algorithm.

Overview

Quick Sort selects a 'pivot' and partitions the array around it.

Complexity

Case Time Space
Best \(O(n \log n)\) \(O(\log n)\)
Average \(O(n \log n)\) \(O(\log n)\)
Worst \(O(n^2)\) \(O(n)\)

Implementation

def quick_sort(arr, low=0, high=None):
    if high is None:
        high = len(arr) - 1

    if low < high:
        pi = partition(arr, low, high)
        quick_sort(arr, low, pi - 1)
        quick_sort(arr, pi + 1, high)

    return arr

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1

    for j in range(low, high):
        if arr[j] < pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1

# Example
arr = [64, 34, 25, 12, 22, 11, 90]
print(quick_sort(arr))
Click to expand solution code
#include <vector>
using namespace std;

int partition(vector<int>& arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;

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

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

How It Works

Array: [8, 3, 1, 7, 0, 10, 2]

  1. Choose pivot: 2
  2. Partition: [1, 0, 2, 8, 3, 7, 10]
  3. Recursively sort left and right

Result: [0, 1, 2, 3, 7, 8, 10]

Advantages

  • ✅ Very efficient for large datasets
  • ✅ In-place sorting
  • ✅ Cache-friendly

Disadvantages

  • ❌ Worst-case \(O(n^2)\)
  • ❌ Not stable