sort.binarySearch: fix integer underflow (#4980)

When the key was smaller than any value in the array, an error was
ocurring with the mid being zero and having 1 subtracted from it.
master
Yuri Pieters 2020-04-09 01:49:42 +01:00
parent c45ba49b8b
commit 447dc2bb90
1 changed files with 3 additions and 3 deletions

View File

@ -10,16 +10,16 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare
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,
}
}