exercism/zig/binary-search/binary_search.zig

22 lines
502 B
Zig
Raw Permalink Normal View History

// 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;
}