fork download
  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  5. int target = 6;
  6.  
  7. int result = binarySearch(sortedArray, target, 0, sortedArray.length - 1);
  8.  
  9. if (result != -1) {
  10. System.out.println("Element " + target + " found at index " + result);
  11. } else {
  12. System.out.println("Element " + target + " not found in the array");
  13. }
  14. }
  15.  
  16. // Recursive Binary Search function
  17. static int binarySearch(int[] arr, int target, int low, int high) {
  18. if (low <= high) {
  19. int mid = low + (high - low) / 2;
  20.  
  21. // If the target is present at the middle
  22. if (arr[mid] == target) {
  23. return mid;
  24. }
  25.  
  26. // If the target is smaller than the middle element, search in the left subarray
  27. if (arr[mid] > target) {
  28. return binarySearch(arr, target, low, mid - 1);
  29. }
  30.  
  31. // If the target is larger than the middle element, search in the right subarray
  32. return binarySearch(arr, target, mid + 1, high);
  33. }
  34.  
  35. // If the target is not present in the array
  36. return -1;
  37. }
  38. }
Success #stdin #stdout 0.16s 57548KB
stdin
Standard input is empty
stdout
Element 6 found at index 5