Created
July 9, 2015 16:24
-
-
Save joshbedo/056429fcb7bfd00a53f3 to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or 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
var list = [1,4,8,10,23,26,55,77,88]; | |
var binarySearch = function(key) { | |
var low = 0; | |
var high = list.length - 1; | |
while(low <= high) { | |
var mid = Math.floor(low + (high - low) / 2); | |
if (key < list[mid]) { | |
high = mid - 1; | |
} else if (key > list[mid]) { | |
low = mid + 1; | |
} else { | |
return mid; | |
} | |
} | |
return -1; | |
} | |
// Returns index of N, if not found returns -1 | |
console.log(binarySearch(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment