Change binary search to return the lowest position
This commit is contained in:
+9
-12
@@ -16,29 +16,26 @@ ol.array.binarySearch = function(haystack, needle, opt_comparator) {
|
|||||||
var mid, cmp;
|
var mid, cmp;
|
||||||
var comparator = opt_comparator || ol.array.numberSafeCompareFunction;
|
var comparator = opt_comparator || ol.array.numberSafeCompareFunction;
|
||||||
var low = 0;
|
var low = 0;
|
||||||
var high = haystack.length - 1;
|
var high = haystack.length;
|
||||||
|
var found = false;
|
||||||
|
|
||||||
while (low <= high) {
|
while (low < high) {
|
||||||
/* Note that "(low + high) >>> 1" may overflow, and results in a typecast
|
/* Note that "(low + high) >>> 1" may overflow, and results in a typecast
|
||||||
* to double (which gives the wrong results). */
|
* to double (which gives the wrong results). */
|
||||||
mid = low + (high - low >> 1);
|
mid = low + (high - low >> 1);
|
||||||
cmp = +comparator(haystack[mid], needle);
|
cmp = +comparator(haystack[mid], needle);
|
||||||
|
|
||||||
/* Too low. */
|
if (cmp < 0.0) { /* Too low. */
|
||||||
if (cmp < 0.0)
|
|
||||||
low = mid + 1;
|
low = mid + 1;
|
||||||
|
|
||||||
/* Too high. */
|
} else { /* Key found or too high */
|
||||||
else if (cmp > 0.0)
|
high = mid;
|
||||||
high = mid - 1;
|
found = !cmp;
|
||||||
|
}
|
||||||
/* Key found. */
|
|
||||||
else
|
|
||||||
return mid;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Key not found. */
|
/* Key not found. */
|
||||||
return ~low;
|
return found ? low : ~low;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user