1. 二分查詢的概念
二分查詢指的是在排好序的陣列中,找到目標元素。如果元素存在則返回元素的下標,不存在則返回-1.
下面以升序為例進行簡單描述
2. 查詢過程:
取陣列中間元素與查詢元素target比較。如果target等於中間元素則直接返回中間元素的下標,如果target小於陣列中間元素則在陣列左邊查詢,如果target大於陣列中間元素則在右邊查詢。重複以上步驟。
3. 二分查詢的時間複雜度
O(logn)
4. Java實現
4.1 迭代版本
public int searchByLoop(int[] arr, int target) {
return searchByLoop(arr, 0, arr.length - 1, target);
}
private int searchByLoop(int[] arr, int low, int high, int target) {
while (low <= high) {
int mid = (low + high) / 2;
if (target == arr[mid]) {
return mid;
} else if (target < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
4.2 遞迴版本
public int searchByRecursion(int[] arr, int target) {
return searchByRecursion(arr, 0, arr.length - 1, target);
}
private int searchByRecursion(int[] arr, int low, int high, int target) {
int mid = (low + high) / 2;
if (target == arr[mid]) {
return mid;
}
if (low > high) {
return -1;
}
if (target < arr[mid]) {
return searchByRecursion(arr, low, mid - 1, target);
}
return searchByRecursion(arr, mid + 1, high, target);
}