版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a281246240/article/details/85599298
二分法查找:二分查找又称折半查找,每次查找,将数据分为两个部分,逐渐缩小查找范围,直到查到数据。
时间复杂度为log2n。
使用二分查找要求:一是必须是顺序存储数据结构,二按关键字有序排列。
/**
* 二分查找法
*/
public class BinarySearch {
/**
* 循环实现
*/
public static int search(int[] t, int d) {
int lowIndex = 0;
int highIndex = t.length - 1;
while(lowIndex <= highIndex) {
int midIndex = (lowIndex + highIndex) / 2;
if (t[midIndex] == d) {
return midIndex;
} else if (d < t[midIndex]) {
highIndex = midIndex - 1;
} else if (d > t[midIndex]) {
lowIndex = midIndex + 1;
}
}
return -1;
}
/**
* 递归实现
*/
public static int search2(int[] t, int d,int high,int low) {
int mid = (high+low)/2;
if(low > high) {
return -1;
}
if(d == t[mid]) {
return mid;
}else if(d > t[mid]) {
return search2(t, d, high, mid+1);
}else if(d < t[mid]) {
return search2(t, d, mid-1, low);
}
return -1;
}
public static void main(String[] args) {
int[] t = {1,4,5,7,9,11,45,56};
System.out.println("re:" + BinarySearch.search(t, 56));
System.out.println("re2:" + BinarySearch.search2(t, 11, t.length-1, 0));
}
}
二分查找法优缺点
优点是查找次数少,性能较高。
缺点是查询的数据表要为有序排列,有一定的局限性。
二分查找适用于不经常变动查找频繁的有序列表。