Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created April 30, 2009 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duncanbeevers/104290 to your computer and use it in GitHub Desktop.
Save duncanbeevers/104290 to your computer and use it in GitHub Desktop.
Array.prototype.binarySearch = function binarySearch(find, comparator, insert) {
if (!comparator) {
comparator = function(a,b) {
return ((a == b) ? 0 : ((a < b) ? -1 : 1)); };
}
var low = 0;
var high = this.length - 1;
var i, comparison;
while (low <= high) {
i = parseInt((low + high) / 2, 10);
comparison = comparator(this[i], find);
if (comparison < 0) { low = i + 1; continue; };
if (comparison > 0) { high = i - 1; continue; };
return i;
}
if (insert) {
return low;
}
return -1;
};
Array.prototype.orderedInsert = function orderedInsert(value, comparator) {
var index = this.binarySearch(value, comparator, true);
this.splice(index, 0, value);
return index;
};
Array.prototype.orderedDelete = function orderedDelete(value, comparator) {
var index = this.binarySearch(value, comparator);
if (index >= 0) {
this.splice(index, 1);
}
return index;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment