本帖最后由 aerkadiya 于 2013-5-17 17:44 编辑
class ChaZhao
{
public static void main(String[] args)
{
int[] arr={2,4,5,7,19,32,45};
int index = halfSearch(arr,32);
int index = halfSearch_2(arr,5);
System.out.println("index="+index);
}
public static int halfSearch_2(int[] arr,int key)
{
int min = 0,max = arr.length-1,mic;
while(min<=max)
{
mid = (max+min)>>1;
if(key>arr[mid])
min = min +1;
else if(key<arr[mid])
max = mid-1;
else
return mid;
}
return -1;
}
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length-1;
mid = (max+min)/2;
while(arr[mid]!=key)
{
if (key>arr[mid])
mid = mid+1;
else if(key<arr[mid])
max = mid-1;
else if(min>max)
return -1;
mid = (max+min)/2;
}
return mid;
}
}
|