Skip to content

Commit

Permalink
Simpler binary search implementation which does not special-case leng…
Browse files Browse the repository at this point in the history
…th=1.
  • Loading branch information
glasser committed May 7, 2013
1 parent 2e9ad51 commit 48774f7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 23 deletions.
32 changes: 11 additions & 21 deletions packages/minimongo/minimongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -695,30 +695,20 @@ LocalCollection._findInOrderedResults = function (query, doc) {
};

// This binary search puts a value between any equal values, and the first
// lesser value. This is to match the previous insertion behaviour of comparing
// each element and inserting it as soon as it compares less than the
// encountered value.
// lesser value.
LocalCollection._binarySearch = function (cmp, array, value) {
if (array.length === 0) return 0;
var lower = 0;
var upper = array.length - 1;

while (lower <= upper) {
var idx = Math.floor( (lower + upper) / 2 );
var comparison = cmp(value, array[idx]);
if (lower === upper) {
if (comparison >= 0) idx++;
return idx;
}
var first = 0, rangeLength = array.length;

if (comparison < 0)
upper = idx;
else
lower = idx + 1;
while (rangeLength > 0) {
var halfRange = Math.floor(rangeLength/2);
if (cmp(value, array[first + halfRange]) >= 0) {
first += halfRange + 1;
rangeLength -= halfRange + 1;
} else {
rangeLength = halfRange;
}
}

// The loop should always end with the lower === upper case.
throw new Error("shouldn't happen");
return first;
};

LocalCollection._insertInSortedList = function (cmp, array, value) {
Expand Down
4 changes: 2 additions & 2 deletions packages/minimongo/minimongo_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1069,10 +1069,10 @@ Tinytest.add("minimongo - binary search", function (test) {

var checkSearchForward = function (array, value, expected, message) {
checkSearch(forwardCmp, array, value, expected, message);
}
};
var checkSearchBackward = function (array, value, expected, message) {
checkSearch(backwardCmp, array, value, expected, message);
}
};

checkSearchForward([1, 2, 5, 7], 4, 2, "Inner insert");
checkSearchForward([1, 2, 3, 4], 3, 3, "Inner insert, equal value");
Expand Down

0 comments on commit 48774f7

Please sign in to comment.