mirror of
https://github.com/ziglang/zig.git
synced 2026-02-21 16:54:52 +00:00
Merge pull request #4982 from MageJohn/fix/binarySearch
sort.binarySearch: fix integer underflow (#4980)
This commit is contained in:
commit
543031db35
@ -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),
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user