Zig Sorting & Searching
Sooner or later every program needs things in order: scores from high to low, names A to Z, events by time. Zig’s standard library sorts any slice in place, with no allocator needed, and you decide what “in order” means by writing a tiny compare function. Once a slice is sorted, you can also search it very quickly with binary search. This lesson covers both, plus the one rule about compare functions that trips people up.
Sorting numbers
Section titled “Sorting numbers”The function you’ll use most is std.mem.sort:
const std = @import("std");
pub fn main() void { var nums = [_]i32{ 42, 7, -3, 19, 7, 0 };
std.mem.sort(i32, &nums, {}, std.sort.asc(i32)); std.debug.print("up: {any}\n", .{nums});
std.mem.sort(i32, &nums, {}, std.sort.desc(i32)); std.debug.print("down: {any}\n", .{nums});}Output:
up: { -3, 0, 7, 7, 19, 42 }down: { 42, 19, 7, 7, 0, -3 }It takes four arguments, and you’ll see the same four in every sort call:
- The item type, here
i32. - The slice to sort. It’s sorted in place, so it must be changeable:
&numsfor an array,list.itemsfor an ArrayList. - A context, extra data for the compare function. We don’t need any here, so we pass
{}, the empty value of typevoid. (More on contexts below.) - The compare function.
std.sort.asc(i32)andstd.sort.desc(i32)are ready-made ones for numbers: smallest first and largest first.
Nothing is returned. nums itself is now in order.
Writing your own compare function
Section titled “Writing your own compare function”For anything beyond plain numbers, you write the compare function yourself. It answers one simple thing: “should a come before b?” Here’s a leaderboard sorted by score, highest first:
const std = @import("std");
const Player = struct { name: []const u8, score: u32,};
fn higherScoreFirst(_: void, a: Player, b: Player) bool { return a.score > b.score;}
pub fn main() void { var players = [_]Player{ .{ .name = "Ana", .score = 30 }, .{ .name = "Bo", .score = 85 }, .{ .name = "Cy", .score = 55 }, .{ .name = "Di", .score = 85 }, };
std.mem.sort(Player, &players, {}, higherScoreFirst);
for (players, 1..) |p, place| { std.debug.print("{d}. {s} ({d})\n", .{ place, p.name, p.score }); }}Output:
1. Bo (85)2. Di (85)3. Cy (55)4. Ana (30)The function’s shape is fixed: fn (context, a: T, b: T) bool. The first parameter is the context; we don’t use it, so it’s named _ with type void. Return true when a should come first. Flip > to < and you get lowest first.
Strings need a little help, because you can’t compare two slices with <. std.mem.lessThan compares them byte by byte, like a dictionary does:
const std = @import("std");
fn alphabetical(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b);}
fn ignoringCase(_: void, a: []const u8, b: []const u8) bool { return std.ascii.lessThanIgnoreCase(a, b);}
fn show(words: []const []const u8) void { for (words, 0..) |w, i| { if (i > 0) std.debug.print(", ", .{}); std.debug.print("{s}", .{w}); } std.debug.print("\n", .{});}
pub fn main() void { var fruit = [_][]const u8{ "pear", "apple", "Fig", "banana", "Apricot" };
std.mem.sort([]const u8, &fruit, {}, alphabetical); show(&fruit);
std.mem.sort([]const u8, &fruit, {}, ignoringCase); show(&fruit);}Output:
Apricot, Fig, apple, banana, pearapple, Apricot, banana, Fig, pearThe first line surprises people: capital letters come before all lowercase ones, because A to Z have smaller byte values than a to z. For a list people will read, compare with std.ascii.lessThanIgnoreCase. (Both of these only know about ASCII letters. Sorting text in other alphabets “correctly” depends on the language and isn’t something the standard library does.)
The context: giving the compare function extra data
Section titled “The context: giving the compare function extra data”The compare function is a plain function, so it can’t see your local variables. That’s what the context is for: whatever you pass as the third argument to sort arrives as the first parameter of the compare function. Here we sort numbers by how close they are to a target, and the target is the context:
const std = @import("std");
fn closerTo(target: i32, a: i32, b: i32) bool { return @abs(a - target) < @abs(b - target);}
pub fn main() void { var guesses = [_]i32{ 10, 52, 47, 38, 61, 50 }; const answer: i32 = 49;
std.mem.sort(i32, &guesses, answer, closerTo); std.debug.print("closest first: {any}\n", .{guesses});}Output:
closest first: { 50, 47, 52, 38, 61, 10 }The context’s type is up to you: an i32 here, often a struct or a slice. If you’ve done JavaScript, this is what you’d normally do with a closure (arr.sort((a, b) => ...) using a variable from outside). Zig has no closures, so you pass the data in explicitly, the same idea as in Zig Function Pointers.
Stable and unstable sorting
Section titled “Stable and unstable sorting”When two items compare as equal (two players with 85 points), which goes first? That’s the difference between the two sorts:
std.mem.sortis stable: equal items keep the order they had before sorting.std.mem.sortUnstableis unstable: equal items may end up in any order. In exchange, it’s usually a bit faster.
Here’s the difference made visible. Forty items are split into three groups, and we check whether each group is still in its original order after sorting by group:
const std = @import("std");
const Item = struct { id: u32, group: u32 };
fn byGroup(_: void, a: Item, b: Item) bool { return a.group < b.group;}
fn keptOrder(items: []const Item) bool { for (items[0 .. items.len - 1], items[1..]) |a, b| { if (a.group == b.group and a.id > b.id) return false; } return true;}
pub fn main() void { var a: [40]Item = undefined; for (&a, 0..) |*item, i| { item.* = .{ .id = @intCast(i), .group = @intCast((i * 7) % 3) }; } var b = a;
std.mem.sort(Item, &a, {}, byGroup); std.mem.sortUnstable(Item, &b, {}, byGroup);
std.debug.print("sort kept the order: {}\n", .{keptOrder(&a)}); std.debug.print("sortUnstable kept the order: {}\n", .{keptOrder(&b)});}Output:
sort kept the order: truesortUnstable kept the order: falseWhen does stability matter? When you sort by one thing and the earlier order still means something. Say your players are already alphabetical and you sort by score: with a stable sort, players with the same score stay alphabetical. With an unstable sort, they get shuffled. If you only care about the sorted field (sorting plain numbers, say), either is fine.
The compare function must be strict
Section titled “The compare function must be strict”This is the mistake to watch for. The compare function must answer “should a come strictly before b?”, so for two equal items it must return false. Writing <= instead of < breaks that rule. In a debug build, Zig’s stable sort notices and stops:
const std = @import("std");
const Item = struct { id: u32, group: u32 };
fn byGroup(_: void, a: Item, b: Item) bool { return a.group <= b.group; // wrong: says equal items come "before" each other}
pub fn main() void { var items: [40]Item = undefined; for (&items, 0..) |*item, i| { item.* = .{ .id = @intCast(i), .group = @intCast((i * 7) % 3) }; } std.mem.sort(Item, &items, {}, byGroup);}You’ll see something like:
thread 4836 panic: reached unreachable code.../lib/std/debug.zig:442:14: 0x102aea9 in assert (std.zig) if (!ok) unreachable; // assertion failure ^.../lib/std/sort/block.zig:110:29: 0x11feeaa in lessThan (std.zig) std.debug.assert(!(lt and gt)); ^The check in block.zig says it plainly: a can’t be both “less than” and “greater than” b. In a fast build there’s no check, and the sort quietly stops keeping its promises: when we ran this with -O fast, the groups came out in order, but equal items were shuffled, so it wasn’t stable any more. So: use < or >, never <= or >=, in a compare function.
Sorting an ArrayList, and a hash map’s keys
Section titled “Sorting an ArrayList, and a hash map’s keys”An ArrayList’s items are a slice, so you sort list.items. That’s also how you print a hash map in order: copy its keys into a list, sort the list, then look the values up.
const std = @import("std");
fn alphabetical(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b);}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var ages: std.StringHashMapUnmanaged(u8) = .empty; defer ages.deinit(gpa); try ages.put(gpa, "Mia", 31); try ages.put(gpa, "Leo", 25); try ages.put(gpa, "Ava", 40); try ages.put(gpa, "Sam", 19);
var names: std.ArrayList([]const u8) = .empty; defer names.deinit(gpa); var it = ages.keyIterator(); while (it.next()) |name| try names.append(gpa, name.*);
std.mem.sort([]const u8, names.items, {}, alphabetical);
for (names.items) |name| { std.debug.print("{s}: {d}\n", .{ name, ages.get(name).? }); }}Output:
Ava: 40Leo: 25Mia: 31Sam: 19The list only holds slices that point at the same bytes as the map’s keys, so it’s cheap: no strings are copied.
Binary search: finding things in a sorted slice
Section titled “Binary search: finding things in a sorted slice”To find a value in an unsorted slice, you have to look at every item. In a sorted slice you can do much better: look at the middle, and throw away the half that can’t contain it. Each step halves what’s left, so even a million sorted items take only about 20 steps. That’s binary search, and it’s std.sort.binarySearch:
const std = @import("std");
fn compareYear(target: u16, item: u16) std.math.Order { return std.math.order(target, item);}
pub fn main() void { const releases = [_]u16{ 2016, 2017, 2018, 2019, 2020, 2022, 2024, 2025 };
const found = std.sort.binarySearch(u16, &releases, @as(u16, 2020), compareYear); const missing = std.sort.binarySearch(u16, &releases, @as(u16, 2021), compareYear);
std.debug.print("2020 is at index {?d}\n", .{found}); std.debug.print("2021 is at index {?d}\n", .{missing});
const spot = std.sort.lowerBound(u16, &releases, @as(u16, 2021), compareYear); std.debug.print("2021 would go at index {d}\n", .{spot});}Output:
2020 is at index 42021 is at index null2021 would go at index 5The search compare function is different from the sort one, so read it carefully:
- It takes the thing you’re looking for (the context) and one item from the slice.
- It returns a
std.math.Order:.lt,.eqor.gt, meaning “what I’m looking for is less than, equal to, or greater than this item”.std.math.order(target, item)builds exactly that for numbers. binarySearchreturns the index as an optional,nullif it’s not there.
std.sort.lowerBound answers a related one: “where would this go?” It returns the index of the first item that isn’t smaller, which is the spot to insert at if you want to keep a list sorted.
Searching without sorting
Section titled “Searching without sorting”For a quick one-off search, sorting first isn’t worth it. These helpers from std.mem walk the slice once:
const std = @import("std");
pub fn main() void { const temps = [_]i32{ 14, 9, 21, 17, 9, 25 };
std.debug.print("first 9 at {?d}\n", .{std.mem.findScalar(i32, &temps, 9)}); std.debug.print("last 9 at {?d}\n", .{std.mem.findScalarLast(i32, &temps, 9)}); std.debug.print("any 30? {}\n", .{std.mem.findScalar(i32, &temps, 30) != null}); std.debug.print("coldest {d}, warmest {d}\n", .{ std.mem.min(i32, &temps), std.mem.max(i32, &temps) });}Output:
first 9 at 1last 9 at 4any 30? falsecoldest 9, warmest 25findScalar returns the index of the first match, or null. (Older code calls it indexOfScalar; Zig 0.17 renamed the indexOf family to find.) Rule of thumb: search a few times, use findScalar; search many times, sort once and use binarySearch, or put the items in a hash map.
Practice
Section titled “Practice”1. Shortest word first
Section titled “1. Shortest word first”Sort [_][]const u8{ "elephant", "ox", "cat", "giraffe", "bee" } by length, shortest first. Words of the same length should stay in their original order.
Hint: compare a.len < b.len, and use std.mem.sort because it’s stable.
Show solution
const std = @import("std");
fn shorterFirst(_: void, a: []const u8, b: []const u8) bool { return a.len < b.len;}
pub fn main() void { var words = [_][]const u8{ "elephant", "ox", "cat", "giraffe", "bee" }; std.mem.sort([]const u8, &words, {}, shorterFirst); for (words) |w| std.debug.print("{s}\n", .{w});}Output:
oxcatbeegiraffeelephantcat and bee are both three letters, and the stable sort keeps cat first because it came first.
2. Sort by two things
Section titled “2. Sort by two things”Sort these people by age, youngest first, and people of the same age by name: Zoe 30, Ali 25, Max 30, Bea 25.
Hint: in the compare function, if the ages differ, compare ages; otherwise compare names with std.mem.lessThan.
Show solution
const std = @import("std");
const Person = struct { name: []const u8, age: u8 };
fn byAgeThenName(_: void, a: Person, b: Person) bool { if (a.age != b.age) return a.age < b.age; return std.mem.lessThan(u8, a.name, b.name);}
pub fn main() void { var people = [_]Person{ .{ .name = "Zoe", .age = 30 }, .{ .name = "Ali", .age = 25 }, .{ .name = "Max", .age = 30 }, .{ .name = "Bea", .age = 25 }, }; std.mem.sort(Person, &people, {}, byAgeThenName); for (people) |p| std.debug.print("{s} {d}\n", .{ p.name, p.age });}Output:
Ali 25Bea 25Max 30Zoe 30Checking the second field only when the first ties is the standard way to sort by several things at once.
3. Is it in the list?
Section titled “3. Is it in the list?”Given the sorted array [_]u32{ 3, 8, 15, 23, 42, 57 }, use binarySearch to report whether 23 and 24 are in it.
Hint: the compare function is fn (target: u32, item: u32) std.math.Order returning std.math.order(target, item). Pass the target as @as(u32, 23).
Show solution
const std = @import("std");
fn cmp(target: u32, item: u32) std.math.Order { return std.math.order(target, item);}
pub fn main() void { const nums = [_]u32{ 3, 8, 15, 23, 42, 57 }; for ([_]u32{ 23, 24 }) |n| { if (std.sort.binarySearch(u32, &nums, n, cmp)) |i| { std.debug.print("{d} found at index {d}\n", .{ n, i }); } else { std.debug.print("{d} is not in the list\n", .{n}); } }}Output:
23 found at index 324 is not in the listInside the loop n already has type u32, so no @as is needed. The if with a capture unwraps the optional index.
std.mem.sort(T, slice, context, lessThan)sorts in place with no allocator. Usestd.sort.asc(T)/desc(T)for numbers.- A compare function answers “should
acome beforeb?” and must be strict:<, never<=. - Compare strings with
std.mem.lessThan(u8, a, b), orstd.ascii.lessThanIgnoreCasefor human-friendly order. - The context passes extra data to the compare function, since Zig has no closures.
std.mem.sortis stable,std.mem.sortUnstablemay reorder equal items.std.sort.binarySearchfinds items in a sorted slice in a few steps; its compare returns astd.math.Order.
Next up: Zig Iterators, the next() pattern you’ve been using all along, and how to write your own.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- std.sort source (0.17.1):
binarySearch,lowerBound,isSortedand the sort algorithms, with diagrams in the doc comments. - std.mem source (0.17.1):
sort,sortUnstable,lessThan,findScalar,minandmax. - Zig language reference: Zig Standard Library: how to find and read the standard library docs.
- zig.guide: Sorting: a short community page. Check which Zig version it targets before copying code.