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 void main(String[] args) {
  11. int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  12. int y = binarySearch(x, 11);
  13. System.out.println(y);
  14. }
  15.  
  16. public static int binarySearch(int[] arr, int value) {
  17. int searchedIndex = -1;
  18. int first = 0;
  19. int last = arr.length - 1;
  20. int mid;
  21.  
  22. while (first <= last) {
  23. mid = (first + last) / 2;
  24. if (arr[mid] == value) {
  25. searchedIndex = mid;
  26. break;
  27. } else {
  28. if (value < arr[mid]) {
  29. last = mid - 1;
  30. } else {
  31. first = mid + 1;
  32. }
  33. }
  34. }
  35.  
  36. return searchedIndex;
  37. }
  38. }
Success #stdin #stdout 0.09s 27848KB
stdin
Standard input is empty
stdout
10