Skip to content

Instantly share code, notes, and snippets.

@eldad87
Last active October 7, 2017 23:12
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 eldad87/cadcd20dba5a4df9603751c254367d25 to your computer and use it in GitHub Desktop.
Save eldad87/cadcd20dba5a4df9603751c254367d25 to your computer and use it in GitHub Desktop.
Add Binary Search capabilities to native Array
/**
* Binary search
*
* @example:
* var arr = [0, 2];
* arr.binarySearch(0) -> true
* arr.binarySearch(2) -> true
* arr.binarySearch(-1)-> false
* arr.binarySearch(1) -> false
* arr.binarySearch(3) -> false
* @param val
* @returns {boolean}
*/
Array.prototype.binarySearch = function(val)
{
var minKey = 0;
var maxKey = this.length -1;
var midKey;
while(minKey <= maxKey) {
midKey = Math.floor((minKey + maxKey) / 2);
if(val === this[midKey]) {
return true;
}
if(val > this[midKey]) {
minKey = midKey+1;
} else {
maxKey = midKey-1;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment