二分查詢法01:遞迴與非遞迴實現
阿新 • • 發佈:2021-10-24
對於有序陣列,才能使用二分查詢法,需要先排序,常應用於需要多次查詢的情況
選定一個標定點,將陣列分為左右兩個區間,時間複雜度為O(logn)
遞迴寫法
public class Algorithm { public static void main(String[] args) { Integer[] arr = {1,2,3,4,5,6,7}; System.out.println(new BinarySearch().search(arr, 4)); } } class BinarySearch { public static<E extends Comparable<E>> int search(E[] arr, E target){ int res = search(arr, 0, arr.length - 1, target); return res; } /** * 迴圈不變數:在arr[left, right]中尋找target */ public static<E extends Comparable<E>> int search(E[] arr, int left, int right, E target){ if (left > right){ return -1; } int mid = left + (right - left) / 2; if (arr[mid].compareTo(target) == 0){ return mid; } else if (arr[mid].compareTo(target) < 0){ return search(arr, mid + 1, right, target); } else { return search(arr, left, mid - 1, target); } } }
非遞迴寫法
public class Algorithm { public static void main(String[] args) { Integer[] arr = {1,2,3,4,5,6,7}; System.out.println(new BinarySearch().search(arr, 4)); } } class BinarySearch { public static<E extends Comparable<E>> int search(E[] arr, E target){ int left = 0; int right = arr.length - 1; /** * 非遞迴寫法,修改邊界的範圍來迴圈查詢 */ while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid].compareTo(target) == 0) { return mid; } if (arr[mid].compareTo(target) < 0) { left = mid + 1; } else { right = mid - 1; } } return -1; } }