Skip to content
Binary Search in JavaScript

Binary Search in JavaScript

Binary search is a better searching algorithm that follows the Divide and Conquer method on the condition that we have sorted/ordered data.

Binary Search Algorithm

We have three variables that drive the search i.e. start, end, and middle. As their name says start will be at the start=0 of the list, the end at the end=list.length of the list, and the middle will be middle = (start+middle)/2.

  • First, we check if our target to search is equal to the value in the middle
  • Then, we compare if our target is less than the middle value
  • If the target < middle less than the middle then we set end = middle and continue searching in the first half
  • else if the target > middle is greater than the middle value then we set start = middle and continue searching in the second half
  • We repeat the above steps until we find the value or when start = end i.e nothing left to search.

Note

  • Binary search can only be performed on sorted data
  • We return the index/position of the element if found else return -1 if not found

Binary Search JavaScript Code

function binarySearch(arr, target) {
  let start = 0;
  let end = arr.length - 1;
  while (start <= end) {
    let middle = Math.floor((start + end) / 2);
    if (arr[middle] === target) {
      return middle;
    }
    if (target < arr[middle]) {
      // start searching in first half before middle
      end = middle - 1;
    } else {
      // start searching in second half after middle
      start = middle + 1;
    }
  }
  return -1;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(binarySearch(arr, 8)); 
// Output: 7 i.e at index 7 of the array we have 8

console.log(binarySearch([1,3,5,7,9,11,13,15], 11));
// Output: 5

console.log(binarySearch([1,3,5,7,9,11,13,15], 1));
// Output: 0

console.log(binarySearch([1,3,5,7,9,11,13,15], 2));
// Output: -1Code language: JavaScript (javascript)

Time Complexity: logarithmicO(log n)

Back to Top