前言:講究的就是一個清晰
原文出處:http://blog.csdn.net/u014158743/article/details/52590544
class Demo
{
public static void main(String[] args)
{
//二分法查找:前提條件:被查找的數組必須是有序的
int[] arr = {23,34,45,56,67,78,89,120};
int key = 99;
int index = halfSearch(arr,key);
System.out.println("index="+index);
}
//二分法查找
//結果:下標或-1
//參數:數組和被找的數
public static int halfSearch(int[] arr,int key)
{
int min = 0,max = arr.length-1,mid;
while(min<=max)
{
mid = (min+max)>>1;
if(key>arr[mid])
min = mid+1;
else if(key<arr[mid])
max = mid-1;
else
return mid;
}
return -1;
}
}