I've tried binary search in my chrome console. But when I've ran the code, the whole chrome got hanged and I had to kill the pages:
var arr = [1, 3, 5, 8];
var binary = function (arr, search) {
var low = 0;
var high = arr.length - 1;
var mid = (high + low) / 2;
while (low <= high) {
if (search === arr[mid]) {
return mid;
} else if (search > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
};
console.log(binary(arr, 3));
In your code,
mid
is always 1.5, because it's calculated before the loop.Instead, move the
mid
calculation within the loop, and calculate it as the rounded average ofhigh
andlow
: