How to implement binary search algorithm in JavaScript

1 Answer

0 votes
function binarySearch(array, element, low, high) {
    while (low <= high) {
        let mid = low + Math.trunc((high - low) / 2);
  
        if (array[mid] == element)
            return mid;
   
        if (array[mid] < element)
            low = mid + 1;
        else
            high = mid - 1;
    }    
    return -1;
}
  
const array = [3, 4, 6, 8, 9, 10, 12, 20, 21, 27, 30, 31, 40, 42];
const number_to_find = 27;
   
const index = binarySearch(array, number_to_find, 0, array.length);
           
if (index == -1) {
    console.log("Not found");
}
else {
    console.log("Found at index: " + index);
}
   

   
   
/*
run:
   
Found at index: 9
   
*/

 



answered Jan 18, 2022 by avibootz
edited Dec 13, 2024 by avibootz

Related questions

1 answer 87 views
1 answer 103 views
1 answer 99 views
1 answer 82 views
1 answer 154 views
3 answers 250 views
2 answers 208 views
...