对于排过序的数组,二分法查找需要的次数大大减少,如数组长度为N ,N = 1000 ,顺序查找平均需要迭代500次,而二分法查找平均只需要迭代8次.
使用三路比较的二分搜索
查找次数:logN(向上取整)-1
/**
*@return index where item is found .or NOT_FOUND.
*final int NOT_FOUND = -1;
*/
public static <AnyType extends comparable<? super AnType>>
int binarySearch(AnyType [] a,AnyType x)
{
if(a.length == 0)
return NOT_FOUND;
int low = 0;
int high = a.length - 1;
int mid;
while(low <= high)
{
mid = (low + high) / 2 ;
if(a[mid].compareTo(x) < 0)
low = mid + 1;
else if(a[mid].compareTo(x) > 0)
high = mid - 1;
else
return mid;
}
return NOT_FOUND;
}
优化:使用二路比较的二分搜索 减少比较次数
比较次数:logN(向上取整)+1
public static <AnyType extends comparable<? super AnyType>>
int binarySearch(AnyType [] a,AnyType x)
{
if(a.length == 0)
return NOT_FOUND;
int low = 0;
int high = a.length-1;
int mid;
while(low < high)
{
mid = (low + high)/2;
if(a.[mid].compareTo(x) < 0)
low = mid + 1;
else
high = mid;
}
if(a[low].compareTo(x) == 0)
return low;
return NOT_FOUND;
}