Last active
October 24, 2018 19:32
-
-
Save nickangtc/4374ea5660f6bbf2b97db5c6d719009f to your computer and use it in GitHub Desktop.
Binary search in JavaScript
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 in JavaScript. | |
* | |
* For detailed explanation about binary search | |
* read my original blog post: | |
* http://www.nickang.com/binary-search-javascript/ | |
*/ | |
function binarySearch(array, key) { | |
var lower = 0; | |
var upper = array.length - 1; | |
var mid; | |
var currentItem; | |
while (lower <= upper) { | |
mid = Math.floor((lower + upper) / 2, 10); | |
currentItem = array[mid]; | |
if (currentItem < key) { | |
lower = mid + 1; | |
} else if (currentItem > key) { | |
upper = mid - 1; | |
} else { | |
return mid; | |
} | |
} | |
return -1; | |
} | |
// test it | |
var input = [0, 2, 40, 44, 48, 55, 66, 99]; | |
console.log(binarySearch(input, 66)); // should print 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment