fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int binarySearch(int[] arr, int target) {
  11. int left = 0, right = arr.length - 1;
  12. while (left <= right) {
  13. int mid = (left + right) / 2;
  14. System.out.println("MID: " + mid);
  15. if (arr[mid] == target) return mid;
  16. else if (arr[mid] < target) left = mid + 1;
  17. else right = mid - 1;
  18. }
  19. return -1;
  20. }
  21.  
  22.  
  23. public static void main (String[] args) throws java.lang.Exception
  24. {
  25. // Test
  26. int[] arr = {1, 3, 5, 7, 9};
  27. int target = 9;
  28. int result = binarySearch(arr, target);
  29. System.out.println(result);
  30. }
  31. }
Success #stdin #stdout 0.13s 55540KB
stdin
Standard input is empty
stdout
MID: 2
MID: 3
MID: 4
4