Advertisement
korobushk

Recursive Binary Search

Mar 22nd, 2021
557
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. public class App {
  2.     public static void main(String[] args) {
  3.  
  4.        
  5.         System.out.println(recursiveBinarySearch(new int[]{1, 2, 3, 4, 7, 9, 12, 18}, 0, 7, 6));
  6.        
  7.        
  8.  
  9.       //  System.out.println(binarySearch(new int[]{3, 11, 21, 29, 41, 54, 61, 78, 110, 127}, 54));
  10.  
  11.     }
  12.  
  13.     public static int recursiveBinarySearch(int[] arr, int first, int last, int value) {
  14.  
  15.         if (first > last) {
  16.             return -1;
  17.         }
  18.         int mid = (first + last) / 2;
  19.         if (arr[mid] == value) {
  20.             return mid;
  21.         } else if (arr[mid] > value) {
  22.             return recursiveBinarySearch(arr, first, mid - 1, value);
  23.         } else {
  24.             return recursiveBinarySearch(arr, mid + 1, last, value);
  25.         }
  26.  
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement