Skip to content

Instantly share code, notes, and snippets.

@AntonisFK
Created April 23, 2016 01:18
Show Gist options
  • Save AntonisFK/32538e744d6a8bea0f4dee30b794033c to your computer and use it in GitHub Desktop.
Save AntonisFK/32538e744d6a8bea0f4dee30b794033c to your computer and use it in GitHub Desktop.
BinarySearch of an array
function binarySearch(array, key) {
var lo = 0,
hi = array.length - 1,
mid,
element;
while (lo <= hi) {
mid = Math.floor((lo + hi) / 2);
element = array[mid];
if (element < key) {
lo = mid + 1;
console.log(lo,"elment < key", mid, array[mid]);
} else if (element > key) {
hi = mid - 1;
console.log(hi, "element > key", mid, array[mid]);
} else {
return mid;
}
}
return -1;
}
var arr = [1,2,3,4,6,7,8,9,10,11,13,15,17,20];
binarySearch(arr, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment