DEV Community

Bvnkumar
Bvnkumar

Posted on

Binary search algorithm implementation in JavaScript

Binary Search:- Binary search algorithm which works based on divide and conquer approach.

  • It is used to search for any element in a sorted array.
  • Compared to linear search, binary search is much faster with time complexity of O(logn) whereas linear search works in O(n) time complexity.
function binarySearch(list, item, left, right) {
    let mid = Math.floor((left + right) / 2)
    if (left > right) {
        console.log(left, right)
        return false
    }
    if (list[mid] == item) {
        return true;
    } else if (item < list[mid]) {
        return binarySearch(list, item, left, mid - 1)
    } else {
        return binarySearch(list, item, mid + 1, right)
    }
}

let list=[1,2,3,5,6,7,8,9];
console.log(binarySearch(list,10,0,list.length-1))
Enter fullscreen mode Exit fullscreen mode

Any comments and suggestions are welcome.

Discussion (0)