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 = 10;
  6.  
  7. int result = binarySearch(sortedArray, target);
  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. // Iterative Binary Search function
  17. static int binarySearch(int[] arr, int target) {
  18. int low = 0;
  19. int high = arr.length - 1;
  20.  
  21. while (low <= high) {
  22. int mid = low + (high - low) / 2;
  23.  
  24. // If the target is present at the middle
  25. if (arr[mid] == target) {
  26. return mid;
  27. }
  28.  
  29. // If the target is smaller than the middle element, search in the left subarray
  30. if (arr[mid] > target) {
  31. high = mid - 1;
  32. }
  33.  
  34. // If the target is larger than the middle element, search in the right subarray
  35. else {
  36. low = mid + 1;
  37. }
  38. }
  39.  
  40. // If the target is not present in the array
  41. return -1;
  42. }
  43. }
Success #stdin #stdout 0.14s 57532KB
stdin
Standard input is empty
stdout
Element 10 found at index 9