Browse Source

Fixed and simplified binary search

v3_develop
jos 10 years ago
parent
commit
d5444a0cba
1 changed files with 16 additions and 47 deletions
  1. +16
    -47
      lib/util.js

+ 16
- 47
lib/util.js View File

@ -1155,62 +1155,31 @@ exports.mergeOptions = function (mergeTarget, options, option) {
* @private
*/
exports.binarySearch = function(orderedItems, range, field, field2) {
var array = orderedItems;
var maxIterations = 10000;
var iteration = 0;
var found = false;
var low = 0;
var high = array.length;
var newLow = low;
var newHigh = high;
var guess = Math.floor(0.5*(high+low));
var value;
var high = orderedItems.length - 1;
if (high == 0) {
guess = -1;
}
else if (high == 1) {
if (array[guess].isVisible(range)) {
guess = 0;
}
else {
guess = -1;
}
}
else {
high -= 1;
while (low <= high && iteration < maxIterations) {
var middle = Math.floor((low + high) / 2);
while (found == false && iteration < maxIterations) {
value = field2 === undefined ? array[guess][field] : array[guess][field][field2];
var item = orderedItems[middle];
if (item.isVisible(range)) { // jihaa, found a visible item!
return middle;
}
if (array[guess].isVisible(range)) {
found = true;
}
else {
if (value < range.start) { // it is too small --> increase low
newLow = Math.floor(0.5*(high+low));
}
else { // it is too big --> decrease high
newHigh = Math.floor(0.5*(high+low));
}
// not in list;
if (low == newLow && high == newHigh) {
guess = -1;
found = true;
}
else {
high = newHigh; low = newLow;
guess = Math.floor(0.5*(high+low));
}
}
iteration++;
var value = (field2 === undefined) ? item[field] : item[field][field2];
if (value < range.start) { // it is too small --> increase low
low = middle + 1;
}
if (iteration >= maxIterations) {
console.log("BinarySearch too many iterations. Aborting.");
else { // it is too big --> decrease high
high = middle - 1;
}
iteration++;
}
return guess;
return -1;
};
/**

Loading…
Cancel
Save