Last active
May 22, 2017 00:56
-
-
Save rodrwan/e2a1d58a1d7dc5cafdb6201f6c18463c to your computer and use it in GitHub Desktop.
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
const arr = [2,3,5,6,23,34,45,86]; | |
const toFind = 23; | |
function indexOf (arr, num) { | |
let low = 0, | |
high = arr.length-1; | |
while (low <= high) { | |
let mid = parseInt((high + low) / 2) | |
let current = arr[mid] | |
if (current > toFind) { // lower part | |
high = mid - 1; | |
} else if (current < toFind) { // upper part | |
low = mid + 1; | |
} else { | |
return mid; | |
} | |
} | |
return -1 | |
} | |
console.log(indexOf(arr, toFind)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment