fork(1) 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.  
  11. public static int binarySearch(int[] arr, int target) {
  12. int left = 0, right = arr.length;
  13. while (left < right) {
  14. int mid = (left + right) / 2;
  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 = 5;
  28. int result = binarySearch(arr, target);
  29. System.out.println(result);
  30.  
  31. }
  32. }
Success #stdin #stdout 0.12s 52448KB
stdin
Standard input is empty
stdout
2