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));

 

About Author

Photo

Hi, I am Mahbub Hasan
Software Engineer

I am very much interested to share my programming
and development knowledge with the people.I will try
to update my blog everyday with new technology inshallah.

Thank You

For Visiting My Blog.

Contact Me