Skip to content

Instantly share code, notes, and snippets.

@rodrwan
Last active May 22, 2017 00:56
Show Gist options
  • Save rodrwan/e2a1d58a1d7dc5cafdb6201f6c18463c to your computer and use it in GitHub Desktop.
Save rodrwan/e2a1d58a1d7dc5cafdb6201f6c18463c to your computer and use it in GitHub Desktop.
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