原文: https://beginnersbook.com/2014/04/java-program-to-perform-binary-search/
在整数列表上执行二分搜索的程序
该程序使用二分搜索算法来在列表中搜索给定元素。
/* Program: Binary Search Example* Written by: Chaitanya from beginnersbook.com* Input: Number of elements, element's values, value to be searched* 输出:Position of the number input by user among other numbers*/import java.util.Scanner;class BinarySearchExample{public static void main(String args[]){int counter, num, item, array[], first, last, middle;//To capture user inputScanner input = new Scanner(System.in);System.out.println("Enter number of elements:");num = input.nextInt();//Creating array to store the all the numbersarray = new int[num];System.out.println("Enter " + num + " integers");//Loop to store each numbers in arrayfor (counter = 0; counter < num; counter++)array[counter] = input.nextInt();System.out.println("Enter the search value:");item = input.nextInt();first = 0;last = num - 1;middle = (first + last)/2;while( first <= last ){if ( array[middle] < item )first = middle + 1;else if ( array[middle] == item ){System.out.println(item + " found at location " + (middle + 1) + ".");break;}else{last = middle - 1;}middle = (first + last)/2;}if ( first > last )System.out.println(item + " is not found.\n");}}
输出 1:
Enter number of elements:7Enter 7 integers4566778990Enter the search value:7777 found at location 4.
输出 2:
Enter number of elements:5Enter 5 integers1237789023Enter the search value:9999 is not found.
