本帖最后由 余银桂 于 2012-6-22 02:15 编辑
- if(arr[mid] < key)
-
- min = mid + 1;
-
- else if(arr[mid] > key)
-
- max = mid - 1;
-
-
- else if(min > max) //为什么这里如果是else if就会进入无限循环?
- //很简单,这句判断是总的if判断的一个条件语句,当前面的有满足条件的,这句就当然永远执行不到了
-
- return -1;
- mid = (min+max)/2;
复制代码 顺道我在帮楼主改了一下代码,供参考!- public static void main(String[] args) {
-
- int [] arr = {1,2,3,4,5,6,7,8,9};
- System.out.println( halfSearch(arr, 9) );
-
- }
- public static int halfSearch( int[] arr,int key ){
-
- int min = 0;
- int max = arr.length-1;
-
- while( min <= max ){
- int mid = (min + max)/2;
- if( arr[mid] < key ){
- min = mid + 1;
- }
- if( arr[mid] > key ){
- max = mid - 1;
- }
- if( arr[mid] == key ){
- return mid;
- }
-
- }
- return -1;
-
- }
复制代码 |