原文: https://beginnersbook.com/2014/04/java-program-to-perform-binary-search/

在整数列表上执行二分搜索的程序

该程序使用二分搜索算法来在列表中搜索给定元素。

  1. /* Program: Binary Search Example
  2. * Written by: Chaitanya from beginnersbook.com
  3. * Input: Number of elements, element's values, value to be searched
  4. * 输出:Position of the number input by user among other numbers*/
  5. import java.util.Scanner;
  6. class BinarySearchExample
  7. {
  8. public static void main(String args[])
  9. {
  10. int counter, num, item, array[], first, last, middle;
  11. //To capture user input
  12. Scanner input = new Scanner(System.in);
  13. System.out.println("Enter number of elements:");
  14. num = input.nextInt();
  15. //Creating array to store the all the numbers
  16. array = new int[num];
  17. System.out.println("Enter " + num + " integers");
  18. //Loop to store each numbers in array
  19. for (counter = 0; counter < num; counter++)
  20. array[counter] = input.nextInt();
  21. System.out.println("Enter the search value:");
  22. item = input.nextInt();
  23. first = 0;
  24. last = num - 1;
  25. middle = (first + last)/2;
  26. while( first <= last )
  27. {
  28. if ( array[middle] < item )
  29. first = middle + 1;
  30. else if ( array[middle] == item )
  31. {
  32. System.out.println(item + " found at location " + (middle + 1) + ".");
  33. break;
  34. }
  35. else
  36. {
  37. last = middle - 1;
  38. }
  39. middle = (first + last)/2;
  40. }
  41. if ( first > last )
  42. System.out.println(item + " is not found.\n");
  43. }
  44. }

输出 1:

  1. Enter number of elements:
  2. 7
  3. Enter 7 integers
  4. 4
  5. 5
  6. 66
  7. 77
  8. 8
  9. 99
  10. 0
  11. Enter the search value:
  12. 77
  13. 77 found at location 4.

输出 2:

  1. Enter number of elements:
  2. 5
  3. Enter 5 integers
  4. 12
  5. 3
  6. 77
  7. 890
  8. 23
  9. Enter the search value:
  10. 99
  11. 99 is not found.