Lesson contents

Quicksort

Choose a pivot and partition the sequence around it. Repeat on each smaller unsorted part.

Simple example

Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.

Start3 1 2
Result1 2 3
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    var values = [_]i64{3, 1, 2};
    const pivot: i64 = values[2];
    var boundary: i64 = 0;
    var i: i64 = 0;
    while (i < 2) {
        if (values[@intCast(i)] < pivot) {
            const saved: i64 = values[@intCast(i)];
            values[@intCast(i)] = values[@intCast(boundary)];
            values[@intCast(boundary)] = saved;
            boundary += 1;
        }
        i += 1;
    }
    values[2] = values[@intCast(boundary)];
    values[@intCast(boundary)] = pivot;
    i = 0;
    while (i < 3) {
        try show(values[@intCast(i)]);
        i += 1;
    }
}
Output
1
2
3
Advertisements

Everyday examples

Divide parcels by a sample weight

Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?

Start8 2 5
Result2 • 5 • 8

Two is lighter and eight is heavier. The pivot now separates the two groups.

Handle equal book prices

Every book costs 4. What would a three-way partition produce?

Start4 4 4
Result∅ • 4 4 4 • ∅

The equal group contains every book. Neither outer group needs more work.

Notice a poor pivot

Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?

Start1 2 3 4
Result1 2 3 • 4 • ∅

One group still holds three items. Repeating this pattern wastes comparisons.

Cost and limits

Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).