How to implement recursive binary search in Node.js

1 Answer

0 votes
function recursive_binary_search(arr, left, right, to_find) {
    if (right >= left) { 
        let mid = Math.ceil(left + (right - left) / 2); 
   
        if (arr[mid] === to_find) 
            return mid; 
     
        if (arr[mid] > to_find) 
            return recursive_binary_search(arr, left, mid - 1, to_find); 
     
        return recursive_binary_search(arr, mid + 1, right, to_find); 
    } 
   
    return -1; 
} 
  
  
const arr = new Array(2, 3, 6, 7, 12, 13, 17, 19, 21, 27); 
const to_find = 12; 
        
const i = recursive_binary_search(arr, 0, arr.length - 1, to_find); 
        
(i === -1) ? console.log("not found") : console.log("Found at index: " + i); 
  
   
    
/*
run:
     
Found at index: 4
        
*/

 

 



answered Dec 13, 2024 by avibootz

Related questions

2 answers 208 views
1 answer 100 views
1 answer 127 views
1 answer 111 views
1 answer 112 views
1 answer 104 views
1 answer 106 views
...