Lesson contents

Merge sort

Split the sequence into smaller parts until each part is sorted. Merge two sorted parts by repeatedly taking their smaller front item.

Simple example

First sort the pairs into 1,3 and 2,4. Compare their front values and print the merged result.

Start3 1 2 4
Result1 2 3 4
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, 4};
    var merged = [_]i64{0, 0, 0, 0};
    var width: i64 = 1;
    while (width < 4) {
        var start: i64 = 0;
        while (start < 4) {
            var left: i64 = start;
            const middle: i64 = (start + width);
            var right: i64 = middle;
            const limit: i64 = (middle + width);
            var pos: i64 = start;
            while (pos < limit) {
                if ((left < middle and (right >= limit or values[@intCast(left)] <= values[@intCast(right)]))) {
                    merged[@intCast(pos)] = values[@intCast(left)];
                    left += 1;
                } else {
                    merged[@intCast(pos)] = values[@intCast(right)];
                    right += 1;
                }
                pos += 1;
            }
            start = limit;
        }
        var i: i64 = 0;
        while (i < 4) {
            values[@intCast(i)] = merged[@intCast(i)];
            i += 1;
        }
        width *= 2;
    }
    var output_index: i64 = 0;
    while (output_index < 4) {
        try show(values[@intCast(output_index)]);
        output_index += 1;
    }
}
Output
1
2
3
4
Advertisements

Everyday examples

Combine two ticket desks

Desk A has tickets 1 and 6. Desk B has 2 and 4. What is the merged order?

Start1 6 / 2 4
Result1 2 4 6

Compare the two fronts. When B is empty, copy A’s remaining ticket.

Merge two dated diaries

Both diaries have a day-5 entry. How can the left diary keep precedence for ties?

Start5A / 5B
Result5A 5B

Choose from the left diary first when dates compare equal. This preserves the prior order.

Combine an empty batch

One folder has no reports. The other has reports 3 and 9 in order. What work remains?

Start∅ / 3 9
Result3 9

Copy the remaining reports directly. There is no pair of fronts to compare.

Cost and limits

Merge sort takes O(n log n) time. A typical array implementation needs extra space for the merged values.