loading...

Binary Search in JavaScript

mbj36 profile image Mohit Bajoria ・1 min read
  • Binary search works on sorted arrays.
  • Binary search begins by comparing an element in the middle of the array with the target value.
  • If the target value matches the element, its position in the array is returned.
  • If the target value is less than the element, the search continues in the lower half of the array. If the target value is greater than the element, the search continues in the upper half of the array.

By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration.

A quick implementation of binary search in JavaScript

Let say's we have a array and we want to search for 7 and return it's index

Alt Text

Iterative Solution

function BinarySearch(arr, value) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

    if (value === arr[mid]) {
      return mid;
    }
    if (val < arr[mid]) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }

  return -1;
}

Recursive Solution

function BinarySearch(arr, value, start = 0, end = arr.length - 1) {
  let mid = Math.floor((start + end) / 2);

  if (arr[value] === mid) {
    return mid;
  }

  if(start >= end) {
      return -1
  }

  return value < arr[mid] ? BinarySearch(arr, value, start, mid - 1) : BinarySearch(arr, value, mid + 1, end)
}

Thanks

Follow me on twitter - https://twitter.com/_mohit_b

Posted on by:

mbj36 profile

Mohit Bajoria

@mbj36

I do web stuffs at indorse.io, built vue-burger-menu

Discussion

markdown guide