exercism/zig/binary-search/binary_search.zig

21 lines
502 B
Zig

// Take a look at the tests, you might have to change the function arguments
const std = @import("std");
pub fn binarySearch(comptime T: type, target: T, array: []const T) ?usize {
var start: usize = 0;
var end: usize = array.len;
while (start < end) {
const mid = start + (end - start) / 2;
if (array[mid] == target) return mid;
if (array[mid] < target) {
start = mid + 1;
} else {
end = mid;
}
}
return null;
}