What does it solve?
Sorts an array by picking a pivot element and partitioning the array around it: everything smaller goes left, everything larger goes right. The pivot lands in its final sorted position.
The two resulting sub-arrays are then sorted recursively using the same process — divide and conquer — until each sub-array has zero or one element.
The core idea (Lomuto partition)
i = low - 1
for j = low to high-1:
if arr[j] < pivot:
i++; swap(arr[i], arr[j])
swap(arr[i+1], arr[high])
Complexity
Average case with balanced partitions. Worst case is O(N²) when the pivot repeatedly lands at an extreme, e.g. already-sorted input with a naive pivot choice.
In-place partitioning — space is only used by the recursion call stack, which is O(N) in the worst case.
Examples & edge cases
Step-by-step table
| Step | Range | Pivot | i | j | Action | Array state |
|---|
C++ implementation (Lomuto partition)
#include <bits/stdc++.h> using namespace std; int partition(vector<int>& arr, int low, int high) { int pivot = arr[high]; // choose last element as pivot int i = low - 1; // boundary of "less than pivot" region for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); // place pivot in final position 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); // left of pivot quickSort(arr, pi + 1, high); // right of pivot } } int main() { vector<int> arr = {10, 80, 30, 90, 40, 50, 70}; quickSort(arr, 0, arr.size() - 1); for (int x : arr) cout << x << " "; cout << "\n"; return 0; }
My Notes