Last active
October 7, 2017 23:12
-
-
Save eldad87/cadcd20dba5a4df9603751c254367d25 to your computer and use it in GitHub Desktop.
Add Binary Search capabilities to native Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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