TExcelTAD
Home › Sorting & Order Statistics › Lomuto Partitioning

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 jj, keeping a boundary ii: everything before ii is known to be smaller than the pivot.

text
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 i

The 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 i=ji = j, since swapping a value with itself changes nothing.

python · try it yourself
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++

cpp · try it yourself
#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 a[lo..hi]a[lo..hi] is cut into four regions:

text
 lo          i            j              hi
 +-----------+------------+--------------+-------+
 |  < pivot  |  >= pivot  |  not yet seen | pivot |
 +-----------+------------+--------------+-------+

Invariant. At the start of each iteration of the for loop, with index jj:

  1. every value in a[lo:i]a[lo:i] is less than the pivot;
  2. every value in a[i:j]a[i:j] is at least the pivot;
  3. a[hi]a[hi] is the pivot.
  • Initialization. Before the first iteration i=j=loi = j = lo, so the first two regions are empty and the claims about them hold trivially. Line 1 read the pivot from a[hi]a[hi], and the loop never touches position hihi.
  • Maintenance. If a[j]≥a[j] \ge pivot, the loop only increases jj, which extends region 2 by a value that belongs there. If a[j]<a[j] < pivot, line 5 swaps it with a[i]a[i], 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 ii and jj go up by one. All three claims still hold.
  • Termination. The loop ends with j=hij = hi, 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 a[lo:i]a[lo:i] is less than the pivot, a[i]a[i] is the pivot, and a[i+1..hi]a[i+1..hi] is at least the pivot. That is a correct partition, and the returned index ii is the pivot's final place in sorted order.

Cost

The loop runs hi−lohi - lo times with one key comparison each, so partitioning mm elements costs exactly m−1m - 1 comparisons and Θ(m)\Theta(m) 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.

python · try it yourself
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, 5040/7=7205040 / 7 = 720 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 lolo and the right part has m−1m - 1 elements. Every partition peels off one element, and quicksort degrades to Θ(n2)\Theta(n^2). 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.

python · try it yourself
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 mm elements?

  1. m−1m - 1, exactly
  2. mlg⁡mm \lg m
  3. between m/2m/2 and mm, depending on the data
  4. 2m2m

During Lomuto partitioning, which region does a value at position kk with i≤k<ji \le k < j belong to?

  1. values less than the pivot
  2. values at least the pivot
  3. values not yet examined
  4. the pivot

After LOMUTO-PARTITION returns pp, what is true of a[p]a[p]?

  1. It is the median of the subarray
  2. It is the pivot, in the position it will have in the sorted array
  3. It is the smallest value of the right part
  4. Nothing in particular

What happens to Lomuto partitioning (with <) when all keys are equal?

  1. The pivot lands in the middle
  2. The pivot lands at lolo and the right part has m−1m - 1 elements, so quicksort takes Θ(n2)\Theta(n^2)
  3. It loops forever
  4. It returns an index outside the subarray