二分查找又稱折半查找,優點是比較次數少,查找速度快;其缺點是要求待查表爲有序表,且插入刪除困難。因此,折半查找方法適用於不經常變動而查找頻繁的有序列表。
該算法要求:
1、 必須採用順序存儲結構。
2、 必須按關鍵字大小有序排列。
該算法時間複雜度最壞爲:O(logn)
注意點有mid、low、high
其Java實現代碼如下(該代碼有缺陷,只是基本實現,有待完善):
public class BinarySearch {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generatedmethod stub
int[] src = {1,3,5,7,8,9};
System.out.println(binarySearch(src,3));
}
private static int binarySearch(int[] src, int i) {
int low=0;
int high=src.length-1;
System.out.println("low is"+low);
System.out.println("high is"+high);
while(low<=high){
int mid = (low+high)/2;
System.out.println("mid is"+mid);
if(src[mid]==i){
return mid;
}else if(i<src[mid]){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
}