diff --git a/lib/std/sort.zig b/lib/std/sort.zig index 3447a0576951..8ed8f2c1c0ec 100644 --- a/lib/std/sort.zig +++ b/lib/std/sort.zig @@ -6,20 +6,17 @@ const math = std.math; const builtin = @import("builtin"); pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compareFn: fn (lhs: T, rhs: T) math.Order) ?usize { - if (items.len < 1) - return null; - var left: usize = 0; - var right: usize = items.len - 1; + var right: usize = items.len; - while (left <= right) { + while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element switch (compareFn(key, items[mid])) { .eq => return mid, .gt => left = mid + 1, - .lt => right = mid - 1, + .lt => right = mid, } } @@ -47,6 +44,10 @@ test "std.sort.binarySearch" { @as(?usize, null), binarySearch(u32, 1, &[_]u32{0}, S.order_u32), ); + testing.expectEqual( + @as(?usize, null), + binarySearch(u32, 0, &[_]u32{1}, S.order_u32), + ); testing.expectEqual( @as(?usize, 4), binarySearch(u32, 5, &[_]u32{ 1, 2, 3, 4, 5 }, S.order_u32),