Lomuto Partitioning
Quicksort is divide and conquer with the work done before the recursive calls instead of after. Merge sort splits the array blindly in the middle and does the real work while merging. Quicksort first partitions: it picks one value, the pivot, and rearranges the array so that everything smaller comes before the pivot and everything else after it. The pivot is then in its final position, and the two sides can be sorted independently, with no merge step at all.
So quicksort is only as good as its partition procedure. This lesson covers the simplest one, named after Nico Lomuto, and proves it correct with a four-region invariant. The Quick Sort lesson in the DSA course is a gentler first look.
The procedure
Lomuto's scheme takes the last element as the pivot and makes one left-to-right pass with an index , keeping a boundary : everything before is known to be smaller than the pivot.
LOMUTO-PARTITION(a, lo, hi) // partitions a[lo..hi] inclusive, returns the pivot's final index
1 pivot = a[hi]
2 i = lo // a[lo:i] holds the values found smaller than the pivot
3 for j = lo to hi - 1
4 if a[j] < pivot
5 swap a[i] and a[j]
6 i = i + 1
7 swap a[i] and a[hi] // the pivot moves between the two parts
8 return iThe animation shows the whole of quicksort; this lesson is about its first partition, the frames up to "Put pivot 5 at position 3".
The Python version prints one line per comparison of the first partition, the "Is … < 5?" frames and the swaps after them. Like the animation, it skips the swap when , since swapping a value with itself changes nothing.
def lomuto_partition(a, lo, hi, trace=False):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
if i != j:
a[i], a[j] = a[j], a[i]
if trace: print(f" is {a[i]} < {pivot}? yes: swap it to position {i} {a}")
elif trace:
print(f" is {a[i]} < {pivot}? yes: already at position {i}")
i += 1
elif trace:
print(f" is {a[j]} < {pivot}? no")
a[i], a[hi] = a[hi], a[i]
if trace: print(f" put pivot {pivot} at position {i} {a}")
return i
a = [6, 3, 8, 1, 9, 2, 5]
p = lomuto_partition(a, 0, len(a) - 1, trace=True)
print(f"left {a[:p]}, pivot {a[p]}, right {a[p + 1:]}") is 6 < 5? no
is 3 < 5? yes: swap it to position 0 [3, 6, 8, 1, 9, 2, 5]
is 8 < 5? no
is 1 < 5? yes: swap it to position 1 [3, 1, 8, 6, 9, 2, 5]
is 9 < 5? no
is 2 < 5? yes: swap it to position 2 [3, 1, 2, 6, 9, 8, 5]
put pivot 5 at position 3 [3, 1, 2, 5, 9, 8, 6]
left [3, 1, 2], pivot 5, right [9, 8, 6]
In C++
#include <cstdio>
#include <utility>
#include <vector>
int lomuto_partition(std::vector<int>& a, int lo, int hi) {
int pivot = a[hi];
int i = lo;
for (int j = lo; j < hi; ++j) {
if (a[j] < pivot) {
std::swap(a[i], a[j]);
++i;
}
}
std::swap(a[i], a[hi]);
return i;
}
void print(const char* label, const std::vector<int>& a, int from, int to) {
std::printf("%s [", label);
for (int k = from; k < to; ++k) std::printf(k > from ? ", %d" : "%d", a[k]);
std::printf("]\n");
}
int main() {
std::vector<int> a = {6, 3, 8, 1, 9, 2, 5};
int p = lomuto_partition(a, 0, static_cast<int>(a.size()) - 1);
print("left ", a, 0, p);
std::printf("pivot %d at index %d\n", a[p], p);
print("right", a, p + 1, static_cast<int>(a.size()));
}left [3, 1, 2]
pivot 5 at index 3
right [9, 8, 6]
The invariant: four regions
At every moment of the loop the subarray is cut into four regions:
lo i j hi
+-----------+------------+--------------+-------+
| < pivot | >= pivot | not yet seen | pivot |
+-----------+------------+--------------+-------+Invariant. At the start of each iteration of the
forloop, with index :
- every value in is less than the pivot;
- every value in is at least the pivot;
- is the pivot.
- Initialization. Before the first iteration , so the first two regions are empty and the claims about them hold trivially. Line 1 read the pivot from , and the loop never touches position .
- Maintenance. If pivot, the loop only increases , which extends region 2 by a value that belongs there. If pivot, line 5 swaps it with , the first value of region 2 (or with itself when region 2 is empty); the small value joins region 1, the displaced large value moves to the end of region 2, and both and go up by one. All three claims still hold.
- Termination. The loop ends with , so the unseen region is empty. Line 7 swaps the pivot with the first value of region 2 (or with itself if region 2 is empty). Now is less than the pivot, is the pivot, and is at least the pivot. That is a correct partition, and the returned index is the pivot's final place in sorted order.
Cost
The loop runs times with one key comparison each, so partitioning elements costs exactly comparisons and time. The number of swaps depends on the data: one per value smaller than the pivot (some of them self-swaps), plus the final pivot swap.
The program partitions every permutation of 7 values and confirms the invariant at every step, the comparison count, and the final property. It also records how often the pivot lands at each position.
from itertools import permutations
from collections import Counter
def partition_checked(a, lo, hi):
pivot, i, comparisons = a[hi], lo, 0
for j in range(lo, hi):
assert all(x < pivot for x in a[lo:i]) and all(x >= pivot for x in a[i:j]) and a[hi] == pivot
comparisons += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i, comparisons
where = Counter()
for perm in permutations(range(7)):
a = list(perm)
p, c = partition_checked(a, 0, 6)
assert c == 6
assert all(x < a[p] for x in a[:p]) and all(x >= a[p] for x in a[p + 1:])
where[p] += 1
print("all 5040 permutations partitioned correctly with 6 comparisons each")
print("pivot's final index:", dict(sorted(where.items())))all 5040 permutations partitioned correctly with 6 comparisons each
pivot's final index: {0: 720, 1: 720, 2: 720, 3: 720, 4: 720, 5: 720, 6: 720}
Each final index appears equally often, times: on a random permutation the pivot is equally likely to be the smallest, the second smallest, … or the largest value. That one fact drives the whole average-case analysis in Randomized Quicksort and Its Expected Cost.
Equal keys: the weak spot
With < in line 4, values equal to the pivot go to the right part. If all keys are equal, nothing is smaller than the pivot, so the pivot ends at position and the right part has elements. Every partition peels off one element, and quicksort degrades to . Changing the test to <= (as in the quickselect animation) just moves the problem: then everything goes left. Either way, many duplicate keys are a real problem for Lomuto's scheme. Hoare's scheme, next lesson, handles them much better, and three-way partitioning handles them perfectly.
def lomuto(a, lo, hi):
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
a = [4] * 8
print("all equal, pivot lands at index", lomuto(a, 0, 7), "of 0..7")
a = [2, 7, 2, 7, 2, 7, 2, 7]
print("two values, pivot lands at index", lomuto(a, 0, 7), "->", a)all equal, pivot lands at index 0 of 0..7
two values, pivot lands at index 4 -> [2, 2, 2, 2, 7, 7, 7, 7]
With two distinct values the first split is even, but each side now holds only equal keys, and from there on every partition peels off a single element.
Test yourself
How many key comparisons does Lomuto partitioning make on a subarray of elements?
- , exactly
- between and , depending on the data
During Lomuto partitioning, which region does a value at position with belong to?
- values less than the pivot
- values at least the pivot
- values not yet examined
- the pivot
After LOMUTO-PARTITION returns , what is true of ?
- It is the median of the subarray
- It is the pivot, in the position it will have in the sorted array
- It is the smallest value of the right part
- Nothing in particular
What happens to Lomuto partitioning (with <) when all keys are equal?
- The pivot lands in the middle
- The pivot lands at and the right part has elements, so quicksort takes
- It loops forever
- It returns an index outside the subarray