前提条件:数组中的数据必须是有序的!
核心思想:每次排除一半的数据,查询数据的性能明显提高很多!
public class Task { public static void main(String[] args) { int[] arr = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}; int rst = binarySearch(arr, 31); System.out.println(rst); } // 二分查找算法 public static int binarySearch(int[] arr, int target) { //声名两个指针【int 值】分别记录数组的起始索引和结束索引 int left = 0; int right = arr.length-1; int index = 0; while (left <= right){ //计算本次mid索引【中间值索引】,判断本次mid对应的原始值是否满足目标元素 int mid = (left+right)/2; if (arr[mid] == target){ return mid; }else if (arr[mid] > target){ right = mid - 1; }else if (arr[mid] < target){ left = mid + 1; } } return -1; }
标签:折半,arr,Java,target,int,mid,查找,public From: https://www.cnblogs.com/yaomagician/p/17165980.html