Created
April 8, 2017 21:02
-
-
Save YozhEzhi/ce4b5e4cbc94938523a0cc6ac1414131 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
function binarySearch(list, item) { | |
let low = 0; | |
let high = list.length - 1; | |
while(low <= high) { | |
let mid = Math.floor((low + high) / 2); | |
let guess = list[mid]; | |
if (guess === item) return guess; | |
if (guess > item) { | |
high = mid - 1; | |
} else { | |
low = mid + 1; | |
} | |
} | |
return null; | |
} | |
const arr = [1, 3, 5, 7, 9]; | |
console.log(binarySearch(arr, 7)); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment