Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. class BinarySearchApp
  2. {
  3.     int binarySearch(int arr[], int l, int r, int x)
  4.     {
  5.         if (r>=l)
  6.         {
  7.             int mid = l + (r - l)/2;
  8.            
  9.             if (arr[mid] == x)
  10.                return mid;
  11.    
  12.             if (arr[mid] > x)
  13.                return binarySearch(arr, l, mid-1, x);
  14.    
  15.             return binarySearch(arr, mid+1, r, x);
  16.         }
  17.         return -1;
  18.     }
  19.  
  20.     public static void main(String args[])
  21.     {
  22.         BinarySearchApp obj = new BinarySearchApp();
  23.         int arr[] = {3,5,9,10,20};
  24.         int n = arr.length;
  25.         int searchKey = 9;
  26.         System.out.println("Array Elements:");
  27.         for(int i : arr) System.out.print(i + " ");
  28.         System.out.println();
  29.         System.out.println("Searching for " + searchKey);
  30.         int result = obj.binarySearch(arr,0,n-1,searchKey);
  31.         if (result == -1)
  32.             System.out.println("Element not found");
  33.         else
  34.             System.out.println("Element found at index " + result);
  35.     }
  36. }
  37.