- 原理
- 优缺点
- 程序范例
原理
折半查找的原理是将排序好的数列分割成两份,然后将要查找的数字与中间位置的数字比较。如果要查找的数字小于中间位置的数字,就可以确定要找的数字在整个数列的前半段,反之在后半段,如果要查找的数字正好与中间位置的数字相等,说明位置已经找到。如此分割数次直到找到或确定不存在为止。
优缺点
折半查找的优点在于比较次数少,查找速度快,平均性能好。
折半查找的缺点在于要求待查表为有序表,且插入删除困难。
程序范例
package boke;
public class Search1 {
public static void main(String[] args) {
int[] a={2,3,5,6,7,9,10};
int s2 = binarySearch(a,7);
System.out.println("7在数组a中的位置是"+s2);
}
public static int binarySearch(int[] a,int num){
if(a.length==0) return -1;
int startPos = 0;
int endPos = a.length-1;
int m = (startPos+endPos)/2;
while(startPos<=endPos){
if(num==a[m]) return m;
if(num>a[m]){
startPos = m+1;
}
if(num<a[m]){
endPos = m-1;
}
m = (startPos+endPos)/2;
}
return -1;
}
}