Binary search program in javascript

Binary Search Program in Javascript

Algorithm, Binary Search, Javascript, Searching, Trending

Binary Search is a technique to search a element in an array with efficient time complexity (Ologn)

In binary search we divide array into halves and check if middle value is equal to searched value. If the values are not equal then we will find the element is left or right array in recursive manner.

We basically ignore half of the elements just after each comparison.

  1. Compare value with the middle element.
  2. If value matches with middle element, we return the mid value.
  3. Else If value is greater than the mid element, then value can only lie in right half subarray after the mid element. So we recur for right half.
  4. Else value is smaller recur in the left half subarray

Lets check out the binary search program in javascript.

function binarySearch(arr, low, high, val) {
    if (high >= low) {

        let mid = Math.floor((low + high) / 2)

        if (arr[mid] == val)
            return mid;

        if (arr[mid] > val)
            return binarySearch(arr, low, mid - 1, val);

        return binarySearch(arr, mid + 1, high, val)
    }
    return -1;
}

let arr = [2, 3, 4, 10, 40];
let val = 3;
console.log(binarySearch(arr, 0, arr.length - 1, val))

Leave a Reply