二分查找的前提是线性表(数组、列表)是已经有序排列的,如果无序则需要先排序。释义参考百度百科
1.循环二分查找
public static int binarySearch(int[] ints, int target) { int start = 0; int end = ints.length - 1; while (start <= end) { /* * int mid = (start + end) / 2; * int mid = start + (end - start) / 2; * 以上两种结果一致,但如果start跟end太大,直接相加会导致溢出,所以应采取第二种可避免溢出 * */ int mid = start + (end - start) / 2; if (target > ints[mid]) { start = mid + 1; } else if (target < ints[mid]) { end = mid - 1; } else { return mid; } } return -1; }
2. 递归二分查找
public static int binarySearchRecursive(int[] ints, int target, int start, int end) { if (start < 0 || end < 0) { return -1; } int mid = start + (end - start) / 2; if (target < ints[mid]) { return binarySearchRecursive(ints, target, start, mid - 1); } else if (target > ints[mid]){ return binarySearchRecursive(ints, target, mid + 1, end); } else { return mid; } }
测试代码
public class BinarySearch { public static void main(String[] args) { int[] ints = {1, 3, 4, 5, 6, 7, 99}; System.out.println(binarySearch(ints, 3)); System.out.println(binarySearch(ints, 0)); System.out.println(binarySearch(ints, -99)); System.out.println("==="); System.out.println(binarySearchRecursive(ints, 3, 0, ints.length - 1)); System.out.println(binarySearchRecursive(ints, 1, 0, ints.length - 1)); System.out.println(binarySearchRecursive(ints, -99, 0, ints.length - 1)); } // 循环二分查找 public static int binarySearch(int[] ints, int target) { int start = 0; int end = ints.length - 1; while (start <= end) { /* * int mid = (start + end) / 2; * int mid = start + (end - start) / 2; * 以上两种结果一致,但如果start跟end太大,直接相加会导致溢出,所以应采取第二种可避免溢出 * */ int mid = start + (end - start) / 2; if (target > ints[mid]) { start = mid + 1; } else if (target < ints[mid]) { end = mid - 1; } else { return mid; } } return -1; } // 递归二分查找 public static int binarySearchRecursive(int[] ints, int target, int start, int end) { if (start < 0 || end < 0) { return -1; } int mid = start + (end - start) / 2; if (target < ints[mid]) { return binarySearchRecursive(ints, target, start, mid - 1); } else if (target > ints[mid]){ return binarySearchRecursive(ints, target, mid + 1, end); } else { return mid; } } }