Files
grokking_algorithms/01_introduction_to_algorithms/zig/binary-search.zig
Paolo Grisoli 8a13efde83 Update examples for Zig (#287)
* update zig in chapters 1-6

* fix zig dijkstras algo

* fix zig greedy algo

* fix longest_common_subsequence in zig

* cleanup

* test: use testing allocator
2024-12-07 07:29:48 -06:00

38 lines
977 B
Zig

const std = @import("std");
const print = std.debug.print;
const expect = std.testing.expect;
pub fn main() void {
const my_list = &[_]i8{ 1, 3, 5, 7, 9 };
print("{?}\n", .{binarySearch(i8, my_list, 3)});
print("{?}\n", .{binarySearch(i8, my_list, -1)});
}
fn binarySearch(comptime T: type, list: []const T, item: T) ?usize {
var low: i32 = 0;
const u_high: u32 = @truncate(list.len);
var high: i32 = @intCast(u_high - 1);
return while (low <= high) {
const mid = @divTrunc((low + high), 2);
const m: usize = @intCast(mid);
const guess = list[m];
if (guess == item) break m;
if (guess > item) {
high = mid - 1;
} else low = mid + 1;
} else null;
}
test "binarySearch" {
const my_list = &[_]i8{ 1, 3, 5, 7, 9 };
var i = binarySearch(i8, my_list, 3);
try expect(i != null);
try expect(i.? == 1);
i = binarySearch(i8, my_list, -1);
try expect(i == null);
}