/** * @desc 二分查询(非递归方式) * 案例: * {1,3,8,10,11,67,100},编程实现二分查找,要求使用非递归方式完成。 * @Author BUG汇总 */ public class BinarySearchNonRecursive { public static void main(String[] args) { int[] arr = {1, 3, 8, 10, 11, 67, 100}; int index = binarySearch(arr, 1); if (index != -1) { System.out.println("找到了,下标为:" + index); } else { System.out.println("没有找到--"); } } private static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] > target) { right = mid - 1; // 向左找 } else { left = mid + 1; // 向右找 } } return -1; } }
二分查找算法(非递归)
冬雷zz 2020-08-25 17:05
经测试,以下写法内存消耗会更少:
public int binarySearch(int[] nums, int target) { int pivot, left = 0, right = nums.length - 1; while (left <= right) { pivot = left + (right - left) / 2; if (nums[pivot] == target) return pivot; if (target < nums[pivot]) right = pivot - 1; else left = pivot + 1; } return -1; }