本帖最后由 王明明 于 2012-7-4 16:59 编辑
class Demo {
public static int half(int []arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length;
while(min<=max)//加上=的号的原因是 当你查找的是2字符的时候 你会发现没加=号 会返回-1 因为min==0 max在mid-1的时候也成了0
{
mid = (min+max)/2;//必须把mid的计算放在循环里面
if(key>arr[mid])
min = mid+1;
else if(key<arr[mid])
max = mid-1;
else
return mid;
}
return -1;
}
public static void main(String[] args) {
int [] arr = {2,3,5,6,8,9,12,35};
int num2 = half(arr,2);
System.out.print(num2);
}
}
或者也可以这样
class Demo {
public static int half(int []arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length;
boolean num = true;
while(num)
{
mid = (min+max)/2;
if(key>arr[mid])
min = mid+1;
else if(key<arr[mid])
max = mid-1;
else if (key == arr[mid])
return mid;
else
num = false;
}
return -1;
}
public static void main(String[] args) {
int [] arr = {2,3,5,6,8,9,12,35};
int num2 = half(arr,2);
System.out.println(num2);
}
}
|