日期:2014-05-20  浏览次数:20700 次

Java折半查找的程序,输出结果总是错位,求教问题出在哪里?
比如输入:{1,2,3,4,5,6,7,8,9,20}
查找:7
输出:
数字已经找到了!6
这个数字在4的后面。
总是不对,求教
代码如下:

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("该数不在数组中。");
     }
 }

}

------解决方案--------------------
这个输出的6,是7所在的下标吧?
在有序数组a[]中查找m,应该返回m在a[]中的下标i才对嘛。不然查询m,然后直接告诉你查询到m,没啥意义了。
------解决方案--------------------
我不知道你的问题在那里,不过程序输出的描述有误
System.out.println("这个数字在" + comparisonCount + "的后面。");
这里的comparisonCount应该是指查询的次数
------解决方案--------------------
根据程序,首先你的position是你找到数字所在数组位置的索引,而你变量comparisonCount准确的说是比较的次数,而根据你的本意,想输出的是lowerbound索引所对应的数字,即System.out.println("这个数字在" + array[lowerbound] + "的后面。");但是这样就存在一个问题,可能存在的情况是(lowerbound + upperbound)/2 也就是position,他的值等于lowerbound,例如lowerbound=4,upperbound=5,求出来的position=4。如果你想要这样的输出结果,可以这样修改:System.out.println("这个数字在" +(lowerbound==position?array[lowerbound-1]:array[lowerbound]) + "的后面。");