二分查找是在完全有序数组(或部分有序)中对某一元素进行快速查找的算法。时间复杂度为O(logn)。
实现方式有递归和非递归。
非递归实现
public int binarySearch(int[] nums, int key) { if (nums == null || nums.length == 0) { return -1; } int low = 0, high = nums.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == key) { return mid; } if (nums[mid] < key) { low = mid + 1; } else { high = mid - 1; } } return -1; }
变形1:查找数组中最接近某一元素(即小于)的元素位置。
public int findMaxMin(int[] nums, int key) { if (nums == null || nums.length == 0) { return -1; } int low = 0, high = nums.length - 1; while (low + 1 < high) { int mid = low + (high - low) / 2; if (nums[mid] < key) { low = mid; } else { high = mid - 1; } } if (nums[high] < key) { return high; } if (nums[low] < key) { return low; } return -1; }