How to implement recursive binary search in TypeScript

1 Answer

0 votes
function recursive_binary_search(arr: number[], left: number, right: number, to_find: number) {
    if (right >= left) { 
        let mid: number = 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: number[] = new Array(2, 3, 6, 7, 12, 13, 17, 19, 21, 28); 
const to_find: number = 13; 
        
const i: number = 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: 5"
        
*/

 

 



answered Dec 13, 2024 by avibootz

Related questions

2 answers 237 views
1 answer 100 views
1 answer 127 views
1 answer 112 views
1 answer 112 views
1 answer 104 views
1 answer 125 views
...