I don’t understand why I got the returne value -1 at every time with any numbers… I want to see the index of the element if it’s presented in arr.
function searchElement2(arr, el) {
let left = -1;
let right = arr.lenght;
while (right - left > 1) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === el) {
return mid;
}
if (arr[mid] > el) {
right = mid;
} else {
left = mid;
}
}
return -1;
}
console.log(searchElement2(arr, 7));
>Solution :
There is a small typo in your code. arr.lenght should be arr.length.
Here’s the corrected version of the code:
function searchElement2(arr, el) {
let left = -1;
let right = arr.length;
while (right - left > 1) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === el) {
return mid;
}
if (arr[mid] > el) {
right = mid;
} else {
left = mid;
}
}
return -1;
}
console.log(searchElement2(arr, 7));
In your original code, arr.lenght is misspelled, which results in right being initialized with undefined. This causes an error in the while loop condition, which causes the loop to exit immediately and return -1.
With the corrected code, arr.length returns the length of the input array, which is used to initialize right. The code should now be able to correctly find the index of the element if it exists in the array, or return -1 if it doesn’t exist.