//为什么我运行着加粗的那句话在这和在while里面的结果都一样呢?
public class HalfSearch {
public static int half_2(int []arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length; mid = (min+max)/2;
while(min<max)
{
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,12);
System.out.print(num2);
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);
}
} 作者: 崔玉朋 时间: 2012-7-4 17:47