二分查找算法
1.二分查找又稱折半查找,它是一種效率較高的查找方法。
2.二分查找要求:(1)必須採用順序存儲結構 (2)必須按關鍵字大小有序排列
3.原理:將數組分爲三部分,依次是前值,中值,後值;將要查找的值和數組的中值進行比較,若小於中值則在中值前 面找,若大於中值則在中值後面找,等於中值時直接返回。然後依次是一個遞歸過程,將前半部分或者後半部分繼續分解爲三部分。
4.實現:二分查找的實現用遞歸和循環兩種方式:
public class BinarySearch {
/**
* 遞歸實現二分查找
* @param dataset 有序數組
* @param target 需要找出target值的下標
*/
public static int binarySearch(int[] dataset, int target, int beginIndex, int endIndex) {
if (target < dataset[beginIndex] || target > dataset[endIndex] || beginIndex > endIndex) {
return -1;
}
int midIndex = (beginIndex + endIndex) / 2;
if (target < dataset[midIndex]) {
return binarySearch(dataset, target, beginIndex, midIndex - 1);
} else if (target > dataset[midIndex]) {
return binarySearch(dataset, target, midIndex + 1, endIndex);
} else {
return midIndex;
}
}
/**
* 循環實現二分查找算法
* @param dataset 有序數組
* @param target 需要找出target值的下標
*/
public static int binarySearch(int[] dataset, int target) {
int low = 0;
int high = dataset.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (target == dataset[middle]) {
return middle;
} else if (target < dataset[middle]) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {6, 12, 33, 87, 90, 97, 108, 561};
System.out.println("遞歸查找:" + binarySearch(arr, 87, 0, arr.length - 1));
System.out.println("循環查找:" + (binarySearch(arr, 87)));
}
}
不管使用那種方式,時間複雜度爲 log2n