- public class text
- {
- public static void main(String[] agrs)
- {
- int[]arr = {1,2,3,4,5};
- int Index = half(arr,2);
- System.out.println("Index = "+Index);
- }
- public static int half(int[] arr,int key)
- {
- int min,max,mid;
- min = 0;
- max = arr.length-1;
- mid = (min+max)/2;//这里已经定义了mid
- while(arr[mid]!=key)
- {
- if(key>arr[mid])
- min = mid+1;
- else if(key<arr[mid])
- max = mid-1;
-
- if(min>max)
- return -1;
- mid = (min+max)/2;//这为什么还要写一次呢
-
- }
- return mid;
- }
- }
复制代码 上面的代码是可以运行的,但是while循环之前已经写了mid = (max+min)/2 为什么在循环里还要写一次 |