Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS for-loop doens't return the correct value

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading