java基础 ——数组折半查找

class BinarySearch
{
public static void main(String[] args)
{
int arr[]={1,2,3,4,5,6,7,};
int temp=search(arr,2);
System.out.println(temp);
}
         // 折半查找前提是:数组必须是有序的

public static int search(int arr[],int key){
int min,max,mid;
min=0;
max=arr.length-1;
mid=(min+max)/2;
while(arr[mid]!=key){
if(arr[mid]<key){
min=mid+1;
}
else if(arr[mid]>key)
max=mid-1;
                          if(min>max)
                               return -1;
mid=(min+max)/2;
}
return mid;
}
}

你可能感兴趣的:(java基础)