有序数组二分查找法
作者:互联网
有序数组二分查找法:
方式1,while循环:
public class BinarySearchTest { public static void main(String[] args) { int[] arr = {1,3,4,7,8,11,15,19,44,48,49}; int target = 50; int result = binarySearch(target,arr); System.out.println("result:" + result); } private static int binarySearch(int target, int[] arr) { int l = 0,r = arr.length - 1,m; while(l<=r){ m = (l + r) >> 1; if(arr[m] == target){ return target; } if(arr[m] > target){ r = m - 1; } if(arr[m] < target){ l = m + 1; } } return -1; } }
方式2,递归:
public class BinarySearchDiGuiTest { public static void main(String[] args) { int[] arr = {1,3,4,7,8,11,15,19,44,48,49}; int target = 2; int result = binarySearch(target,arr); System.out.println("result:" + result); } private static int binarySearch(int target, int[] arr) { int l = 0,r = arr.length - 1,m = 0; int result = search(l,r,m,arr,target); return result; } private static int search(int l, int r, int m,int[] arr,int target) { m = (l + r) >> 1; if(arr[m] == target){ return target; } if(arr[m] > target){ r = m - 1; } if(arr[m] < target){ l = m + 1; } if(l <= r){ return search(l,r,m,arr,target); } return -1; } }
算法理解思路很重要。
标签:二分,arr,target,int,binarySearch,查找,static,result,数组 来源: https://www.cnblogs.com/super-chao/p/16528219.html