本帖最后由 忘记了 于 2013-11-24 01:25 编辑
public class halfSearch {
public static void main(String[] args)
{
int[] arr = {1,2,3,4,5,6,7,};
int index1 = halfSearch_1(arr,4);
int index2 = halfSearch_2(arr,7);
System.out.println("index1="+index1);
System.out.println("index2="+index2);
}
public static int halfSearch_1(int[] arr,int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=min+max/2;
while(arr[min]!=key)
{
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
mid=(max+min)/2;
if(min>max)
return -1;
}
return mid;
}
public static int halfSearch_2(int arr[],int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
while(min<=max)
{
mid=(min+max)/2;
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
else
return mid;
}
return -1;
}
}
//运行完了没看见输出?? |