This code block works perfectly . This is a binary search algorithm written in javascript. I collected it from a website.
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
var result = binarySearch([2,3,4,5,6,7,8,9,10],2);
console.log(result);
But if i change the code inside the while loop this way it doesn't work . I have tried several times but to no avail. Please help me. What is the problem?
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
// Look here. Here is my problem
if(arr[mid] > target){
right = mid - 1;
}
}
return -1;
}
var result = binarySearch([2,3,4,5,6,7,8,9,10],2);
console.log(result);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
if(arr[mid] > target){
right = mid - 1;
}
and
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
Are equivalent in this scenario.