How to implement recursive binary search in Java

1 Answer

0 votes
public class MyClass {
    static int recursive_binary_search(int arr[], int left, int right, int to_find) {        
        if (right >= left) {
            int mid = 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;    
    }
    public static void main(String args[]) {
        int arr[] = {1, 2, 3, 4, 21, 13, 30, 50};
         
        int to_find = 13;        
        int result = recursive_binary_search(arr, 0, arr.length - 1, to_find);        
         
        if (result == -1)            
            System.out.println("Not Found");        
        else          
            System.out.println("Found at index: " + result);    
  
    }
}
  
  
/*
run:
  
Found at index: 5
  
*/

 



answered Aug 5, 2019 by avibootz
edited Aug 5, 2019 by avibootz

Related questions

1 answer 116 views
1 answer 140 views
1 answer 128 views
1 answer 123 views
1 answer 122 views
1 answer 120 views
1 answer 141 views
...