Adding Binary Search

This commit is contained in:
akashsolanki1101 2019-10-31 20:23:22 +05:30 committed by GitHub
parent dc1047df72
commit 7813d5ec62
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,27 @@
var myList = [1, 3, 5, 7, 9];
function binarySearch(myList, itemToFind) {
var low = 0,
high = myList.length - 1,
mid,
guessed;
while(low <= high) {
mid = Math.floor((low + high) / 2),
guessed = myList[mid];
if(guessed === itemToFind) {
console.log('Found item at index: ' + mid + ', value is ' + guessed);
return;
}
if(itemToFind < guessed) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return null;
}
binarySearch(myList, 3);