- //有两个问题.
- public class Demo7_2 {
- public static void main(String[] args) {
- // 折半查找
- int[] arr = { 1, 5 };
- int index = HalfSearch(arr, 5);
- System.out.println("Index=" + index);
- }
- public static int HalfSearch(int[] arr, int key) {
- int min, max, mid;
- min = 0;
- max = arr.length - 1;
- mid = (min + max) / 2;
- do {
- if (key < arr[mid])
- max = mid - 1;
- else if (key > arr[mid])
- min = mid + 1;
- mid = (min + max) / 2;
- } while (key == arr[mid]);//第一,这里的判断条件是key == arr[mid]
- //也就是当相等了就继续进去查找,不等就不管了....
-
- return arr[mid];//第二,这里你返回的是arr[]数组中指数锁对应的值,也就是五,而你想要的是指数...
- }
- }
复制代码 |