BinarySearch.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Java implementation of recursive
  2. // Binary Search
  3. class BinarySearch {
  4. // Function that returns index of
  5. // x if it is present in arr[l, r]
  6. int binarySearch(int arr[], int l,int r, int x) {
  7. if (r >= l) {
  8. int mid = l + (r - l) / 2;
  9. // If the element is present
  10. // at the middle itself
  11. if (arr[mid] == x)
  12. return mid;
  13. // If element is smaller than
  14. // mid, then it can only be
  15. // present in left subarray
  16. if (arr[mid] > x)
  17. return binarySearch(arr, l, mid - 1, x);
  18. // Else the element can only be
  19. // present in right subarray
  20. return binarySearch(arr, mid + 1, r, x);
  21. }
  22. // Reach here when element is
  23. // not present in array
  24. return -1;
  25. }
  26. // Driver Code
  27. public static void main(String args[]) {
  28. // Create object of this class
  29. BinarySearch ob = new BinarySearch();
  30. // Given array arr[]
  31. int arr[] = { 2, 3, 4, 10, 40 };
  32. int n = arr.length;
  33. int x = 10;
  34. // Function Call
  35. int result = ob.binarySearch(arr, 0, n - 1, x);
  36. if (result == -1)
  37. System.out.println("Element " + "not present");
  38. else
  39. System.out.println("Element found" + " at index " + result);
  40. }
  41. }