How to implement binary search algorithm in Node.js

2 Answers

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, 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: 8
        
*/

 



answered Jan 18, 2022 by avibootz
edited Mar 23, 2025 by avibootz
0 votes
function binary_search(arr, to_find) {
    let left = 0;
    let right = arr.length - 1;
    let mid = 0;
     
    while (left <= right) { 
        mid = Math.ceil(left + (right - left) / 2); 
       
        if (arr[mid] === to_find) 
            return mid; 
       
        if (arr[mid] < to_find) 
            left = mid + 1; 
        else
            right = mid - 1; 
    } 
       
    return -1; 
}  
   
   
const arr = new Array(2, 3, 6, 7, 9, 12, 14, 17, 19, 21, 30); 
const to_find = 14; 
         
const i = binary_search(arr, to_find); 
         
(i === -1) ? console.log("not found") : console.log("Found at index: " + i); 
  
 
 
/*
run:
      
Found at index: 6
         
*/

 



answered Mar 23, 2025 by avibootz

Related questions

1 answer 124 views
1 answer 160 views
1 answer 213 views
1 answer 86 views
1 answer 102 views
1 answer 98 views
...