My attempt to implement the binary search algorithm in my code example is not producing the expected result. I'm unsure of the cause. Can someone please explain it to me?
var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80];
function binarySearch (array, numberToSearch) {
var firstIndex = 0;
var lastIndex = array.length - 1;
var currentIndex;
var currentElement;
currentIndex = (lastIndex + firstIndex) / 2 | 2;
currentElement = array[currentIndex];
while (firstIndex <= lastIndex) {
if (numberToSearch === currentElement) {
// found
console.log(currentIndex);
return currentIndex;
} else if (numberToSearch < currentElement) {
lastIndex = currentIndex - 1;
currentIndex = (lastIndex + firstIndex) / 2 | 2;
currentElement = array[currentIndex];
} else if (numberToSearch > currentElement) {
firstIndex = currentIndex + 1;
currentIndex = (lastIndex + firstIndex) / 2 | 2;
currentElement = array[currentIndex];
}
}
return -1;
}
binarySearch(array, 12);
When running the function with the value of 12, I should be getting a result of 5, but nothing is happening.