aboutsummaryrefslogtreecommitdiff
path: root/lib/std
diff options
context:
space:
mode:
Diffstat (limited to 'lib/std')
-rw-r--r--lib/std/sort.zig13
1 files changed, 7 insertions, 6 deletions
diff --git a/lib/std/sort.zig b/lib/std/sort.zig
index 3447a05769..8ed8f2c1c0 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,
}
}
@@ -48,6 +45,10 @@ test "std.sort.binarySearch" {
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),
);