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. public class Main {
  9. public int Search(int[] a, int x) {
  10. int low = 0;
  11. int high = a.length - 1;
  12. Boolean search=false;
  13. while (low <= high && !search) {
  14. int mid = (low + high)/2;
  15. if (a[mid] == x) {
  16. search=true;
  17. return mid;
  18. }
  19. else if (a[mid] < x) low = mid + 1;
  20. else high = mid - 1;
  21. }
  22. return -1;
  23. }
  24.  
  25.  
  26. public static void main(String[] args) {
  27. Main bin = new Main();
  28. int[] a ={ 2, 8,12,14,16,19,24,28,31,33,// 0-9
  29. 39,40,45,49,51,53,54,56,57,60,// 10-19
  30. 63,69,77,82,88,89,94,96,97}; // 20-28
  31. Scanner input = new Scanner(System.in);
  32. System.out.println("Enter the number you whould like to search !");
  33. int n=input.nextInt();
  34. int index=bin.Search(a,n);
  35. if(index<0) { //-1 means that the element doesn't exist in the array
  36. System.out.println("This number doesn't exist in the array ");
  37. } else {
  38. System.out.println("The index of the number "+n+" in the array is :"+ index);
  39. }
  40.  
  41. }
  42. }
Success #stdin #stdout 0.15s 321088KB
stdin
8

stdout
Enter the number you whould like to search !
The index of the number 8 in the array is :1