日期:2014-05-20 浏览次数:20727 次
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keynum = new Scanner(System.in);
Scanner inputnum = new Scanner(System.in);
System.out.println("请输入十个整数:");
int[ ] num = new int [10];
for (int i = 0; i < 10; i++)
{
num[ i ] = inputnum.nextInt();
}
System.out.println("请输入要查找的数:");
int key = inputnum.nextInt();
binarySearch (num, 0, 9, key); //折半查找
}
public static void binarySearch(int[ ] array, int lowerbound, int upperbound, int key){
int position;
int comparisonCount = 1; //比较数的计数器.
position = ( lowerbound + upperbound) / 2; //先找出中间位置
while((array[position] != key) && (lowerbound <= upperbound))
{
comparisonCount++;
if (array[position] > key)
{
upperbound = position - 1; //如果数字大于要查找的数字,则向low靠拢
}
else
{
lowerbound = position + 1; //否则,向high靠拢
}
position = (lowerbound + upperbound) / 2; //重复在子区间折半
}
if (lowerbound <= upperbound)
{
System.out.println("数字已经找到了!" + position);
System.out.println("这个数字在" + comparisonCount + "的后面。");
}
else
{
System.out.println("该数不在数组中。");
}
}
}