Util: fix binary search exit condition
The loop can exit with an interval of length one or one of length zero. In the first case it is correct to check which side of the interval to return, in the second case no comparison should be made (since there is only one possible value). In practice, this usually results in one comparison more than needed, but in some cases (when the position was past the end of the array), would call the comparator with undefined. https://bugzilla.gnome.org/show_bug.cgi?id=666614
This commit is contained in:
parent
087d8e602e
commit
bbdce159fa
@ -265,7 +265,7 @@ function lowerBound(array, val, cmp) {
|
||||
max = mid;
|
||||
}
|
||||
|
||||
return (cmp(array[min], val) < 0) ? max : min;
|
||||
return (min == max || cmp(array[min], val) < 0) ? max : min;
|
||||
}
|
||||
|
||||
// insertSorted:
|
||||
|
@ -64,8 +64,13 @@ let arrayEmpty = [];
|
||||
// inserting in a empty array
|
||||
Util.insertSorted(arrayEmpty, 3, checkedCmp);
|
||||
|
||||
// Insert at the end and check that we don't
|
||||
// access past it
|
||||
Util.insertSorted(arrayEmpty, 4, checkedCmp);
|
||||
Util.insertSorted(arrayEmpty, 5, checkedCmp);
|
||||
|
||||
// Some more insertions
|
||||
Util.insertSorted(arrayEmpty, 2, checkedCmp);
|
||||
Util.insertSorted(arrayEmpty, 1, checkedCmp);
|
||||
|
||||
assertArrayEquals('checkedCmp test', [1, 2, 3], arrayEmpty);
|
||||
assertArrayEquals('checkedCmp test', [1, 2, 3, 4, 5], arrayEmpty);
|
||||
|
Loading…
Reference in New Issue
Block a user