Sub topic 3
The Lomuto Partition Scheme
This chapter assumes you can read Python, trace index-based loops over arrays, and know what partitioning around a pivot means: after the step, smaller elements sit to the pivot's left and larger ones to its right. Here we look at one concrete way to do that, the Lomuto scheme. We cover its loop invariant, a full trace, its exact cost, and the edge cases that commonly break implementations of it.
What Lomuto Promises
Lomuto partitioning works on the subarray a[lo..hi], inclusive at both ends. It uses a[hi] as the pivot and returns an index p. When it returns, these conditions hold:
a[p]holds the pivot value.- Every element in
a[lo..p-1]is strictly less than the pivot. - Every element in
a[p+1..hi]is greater than or equal to the pivot. - Nothing outside
a[lo..hi]was touched.
Because the pivot ends at its final sorted position, the recursive calls can skip index p entirely. That fact sets the recursion bounds used in the next chapter.
The Code
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = 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 iThe function uses two indices. j scans every element except the pivot, from left to right. i marks the boundary: it is the position where the next "small" element should go.
The Loop Invariant
Lomuto is easiest to reason about through its invariant. At the start of each loop iteration, the subarray is split into four regions:
| Region | Indices | Contents |
|---|---|---|
| Small | `lo .. i-1` | Elements `< pivot` |
| Large | `i .. j-1` | Elements `>= pivot` |
| Unexamined | `j .. hi-1` | Not yet compared |
| Pivot | `hi` | The pivot value |
The invariant holds at the start because i = j = lo, so the small and large regions are both empty. Each iteration keeps it true:
- If
a[j] >= pivot, the element already sits at the right end of the large region. Advancingjextends that region by one. - If
a[j] < pivot, the code swaps it witha[i], which is the first element of the large region. That large element moves to positionj, still inside the large region. The small element lands ati, and incrementingigrows the small region by one.
When the loop ends, j == hi and the unexamined region is empty. The final swap exchanges the pivot with a[i], the first large element. If the large region is empty, a[i] is the pivot itself. Either way the pivot lands between the two regions, and the four conditions above hold.
A Full Trace
Partition [7, 2, 9, 4, 1, 5] with lo = 0 and hi = 5. The pivot is 5.
| j | a[j] | a[j] < 5? | Action | i after | Array after |
|---|---|---|---|---|---|
| start | 0 | `[7, 2, 9, 4, 1, 5]` | |||
| 0 | 7 | no | none | 0 | `[7, 2, 9, 4, 1, 5]` |
| 1 | 2 | yes | swap a[0], a[1] | 1 | `[2, 7, 9, 4, 1, 5]` |
| 2 | 9 | no | none | 1 | `[2, 7, 9, 4, 1, 5]` |
| 3 | 4 | yes | swap a[1], a[3] | 2 | `[2, 4, 9, 7, 1, 5]` |
| 4 | 1 | yes | swap a[2], a[4] | 3 | `[2, 4, 1, 7, 9, 5]` |
| end | swap a[3], a[5] | 3 | `[2, 4, 1, 5, 9, 7]` |
The function returns 3. The left side [2, 4, 1] is all below 5 and the right side [9, 7] is all above it. Neither side is sorted, and partitioning does not need it to be.
Exact Cost
Lomuto's cost is easy to count, and the complexity chapter relies on these numbers.
- Comparisons: exactly
hi - lo, one per non-pivot element. That isn - 1for a subarray ofnelements, whatever the data. - Swaps: one for each element less than the pivot, plus the final swap. This ranges from 1 to
n. - Extra memory: O(1). Only the variables
i,j, andpivotare used.
Some of those swaps exchange an element with itself. This happens when i == j, meaning no large element has appeared yet. On an already sorted input, every swap in the loop is a self-swap. A self-swap is harmless, and you can skip it with if i != j. In Python the saving is negligible. In languages where swapping large records is expensive, it can matter.
Checking It Against Its Contract
A randomized test that asserts the postconditions catches most off-by-one mistakes quickly. Small value ranges make duplicates common, which is where bugs tend to hide.
import random
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = 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
def check_partition(a, lo, hi):
before = a[lo:hi + 1]
outside = a[:lo] + a[hi + 1:]
pivot = a[hi]
p = lomuto_partition(a, lo, hi)
assert lo <= p <= hi
assert a[p] == pivot
assert all(x < pivot for x in a[lo:p])
assert all(x >= pivot for x in a[p + 1:hi + 1])
assert sorted(a[lo:hi + 1]) == sorted(before)
assert a[:lo] + a[hi + 1:] == outside
random.seed(1)
for _ in range(10000):
n = random.randint(1, 12)
a = [random.randint(0, 5) for _ in range(n)]
lo = random.randint(0, n - 1)
hi = random.randint(lo, n - 1)
check_partition(a, lo, hi)
print("all checks passed")Edge Cases
A single element
When lo == hi, the loop body never runs, the final swap exchanges a[hi] with itself, and the function returns lo. This is correct. Quicksort usually doesn't call partition on such ranges anyway.
All elements equal
With the strict < test, no element is ever smaller than the pivot, so i stays at lo. The pivot moves to index lo, and the "greater or equal" side gets all n - 1 remaining elements.
a = [4, 4, 4, 4, 4]
print(lomuto_partition(a, 0, 4)) # 0Every split is as lopsided as possible, so quicksort on an array of identical keys takes quadratic time. Changing < to <= does not help: every element then counts as small, and the pivot ends at hi. That is just as lopsided, on the other side. The real fix is three-way partitioning, covered later in the tutorial.
Already sorted input
If the subarray is sorted, the last element is its maximum. Every other element is smaller, so p = hi and the right side is empty. This is the classic worst case for a last-element pivot, analyzed in the chapter on quadratic inputs.
Common Implementation Errors
Using a different pivot without moving it
Lomuto's final swap assumes the pivot sits at a[hi]. To use the middle element or a random element as the pivot, first swap it into position hi, then run the unchanged function. If you set pivot = a[mid] and leave it in place, the final swap moves the wrong element, and the returned index no longer holds the pivot.
Scanning the pivot too
Writing range(lo, hi + 1) makes the loop compare the pivot against itself. With < this happens to be harmless, because pivot < pivot is false. With <= it breaks the function: the pivot gets swapped into the small region and i moves past it, so the final swap puts a large element in the wrong place. Keep the bound at hi.
Forgetting the final swap
Without the last swap, a[i] holds some large element, not the pivot. A caller that excludes index p from recursion would then skip an unsorted element. The output can look almost sorted, which makes this bug easy to miss in small tests.
Mixing in Hoare's recursion bounds
Lomuto's caller recurses on lo..p-1 and p+1..hi. Hoare's caller recurses on lo..p and p+1..hi. Using one scheme's partition function with the other's bounds causes either infinite recursion or unsorted output.
Exercise
Trace lomuto_partition on [3, 8, 2, 5, 1, 4] with lo = 0 and hi = 5. What array results, and what index is returned?
Show answer
The pivot is 4. j=0: 3 < 4, swap a[0] with itself, i=1. j=1: 8, no action. j=2: 2 < 4, swap a[1] and a[2] giving [3, 2, 8, 5, 1, 4], i=2. j=3: 5, no action. j=4: 1 < 4, swap a[2] and a[4] giving [3, 2, 1, 5, 8, 4], i=3. The final swap of a[3] and a[5] gives [3, 2, 1, 4, 8, 5]. The function returns 3.
Exercise
How many comparisons and how many swaps (counting self-swaps and the final swap) does lomuto_partition perform on [1, 2, 3, 4, 5] with lo = 0, hi = 4?
Show answer
It makes 4 comparisons, one per non-pivot element. All four are less than the pivot 5, so the loop makes 4 swaps, all of them self-swaps because i equals j each time. The final swap exchanges a[4] with itself, for 5 swaps in total. The returned index is 4.
Exercise
You want to use the middle element a[(lo + hi) // 2] as the pivot without changing the body of lomuto_partition. What one line do you add, and where?
Show answer
Before calling lomuto_partition (or at the very start of it, before pivot = a[hi]), add: mid = (lo + hi) // 2; a[mid], a[hi] = a[hi], a[mid]. This moves the chosen pivot into position hi, where the final swap expects it.