Binary Search Algorithm in JavaScript
Binary Search Algorithm using JavaScript
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function binarySearch(arr, element) {
let result = true;
let firstIndex = 0;
let lastIndex = arr.length - 1;
while (firstIndex <= lastIndex) {
let mid = (firstIndex + lastIndex)/2;
if (arr[mid] === element) {
result = false;
return `Element ${element} found in index ${mid}`;
}
else if (element < arr[mid]) {
lastIndex = mid - 1;
}
else {
firstIndex = mid + 1;
}
}
if (result) {
return `Element ${element} is not found`;
}
}
console.log(binarySearch(myArray, 5));