🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Sorting

Sorting is putting values into a chosen order, such as smallest to largest. Zig sorts an array in place, so the original array changes instead of a new one appearing.

Ascending sort orders smallest first

The sort call reorders the array in place. The printout shows 1, then 3, then 4.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var nums = [_]i32{ 3, 1, 4 };
    std.mem.sort(i32, &nums, {}, comptime std.sort.asc(i32));
    try out.print("{any}\n", .{nums});
}

Descending sort orders largest first

Only the order rule changes in this call. The printout now starts at 5 and ends at 1.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var nums = [_]i32{ 3, 1, 4, 1, 5 };
    std.mem.sort(i32, &nums, {}, comptime std.sort.desc(i32));
    try out.print("{any}\n", .{nums});
}

Sorting a slice sorts only that part

The sort receives a slice of the first three values. Those values order themselves, and the last value stays 4.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var nums = [_]i32{ 9, 2, 7, 4 };
    std.mem.sort(i32, nums[0..3], {}, comptime std.sort.asc(i32));
    try out.print("{any}\n", .{nums});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var scores = [_]i32{ 42, 7, 19, 7, 30 };
    try out.print("{any}\n", .{scores});
    std.mem.sort(i32, &scores, {}, comptime std.sort.asc(i32));
    try out.print("{any}\n", .{scores});
    try out.print("{d}\n", .{scores[0]});
    try out.print("{d}\n", .{scores[scores.len - 1]});
}

Key points

  • std.mem.sort: this helper sorts the values of an array in place.
  • Type argument: the first argument names the type of the values being sorted.
  • Array argument: &nums hands the sort helper the array itself, so the helper can change it.
  • Ascending: std.sort.asc(i32) orders values from smallest to largest.
  • Descending: std.sort.desc(i32) orders values from largest to smallest.
  • In place: after an ascending sort, the first value is the smallest and the last value is the largest.

In this example, the scores print in their starting order first. The sort call then reorders the same array from smallest to largest. The last printouts show the smallest score 7 at index 0 and the largest score 42 at the final index.

Note

sorting changes the array, so the array must be declared with var.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After an ascending sort of [_]i32{ 5, 2, 8 }, what sits at index 0?