Last active
April 9, 2018 09:24
-
-
Save steverydz/e7ddb319e3f66cad90ca27a80ccb2672 to your computer and use it in GitHub Desktop.
JavaScript binary search algorithm
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
function binarySearch(list, item) { | |
var low = 0; | |
var high = list.length - 1; | |
while (low <= high) { | |
var mid = low + Math.floor((low + high) / 2); | |
var guess = list[mid]; | |
if (guess === item) { | |
return mid; | |
} | |
if (guess > item) { | |
high = mid - 1; | |
} else { | |
low = mid + 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment