8.二分查找法

1.思路分析

 

 2.代码实现

 1 //  二分查找法
 2 public class BinarySearch {
 3     public static void main(String[] args) {
 4         int[] arr = {1, 4, 7, 9, 11, 15, 22, 27, 33, 48, 50, 101};
 5         System.out.println(search(arr,101));
 6     }
 7 
 8     private static int search(int[] arr,int target) {
 9         return binarySearch(arr, 0, arr.length - 1, target);
10     }
11 
12     private static int binarySearch(int[] arr, int left, int right,int target) {
13         if(left > right)
14             //  如果左下标大于右下标,说明没找到返回-1
15             return -1;
16         int mid = (left + right) / 2;
17         if (target > arr[mid]) {
18             //  目标在右半区,递归右半区
19             return binarySearch(arr,mid + 1, right,target);
20         } else if (target < arr[mid]) {
21             //  目标在左半区,递归左半区
22             return binarySearch(arr, right, mid - 1, target);
23         } else
24             return mid;
25     }
26 }

 

posted on 2020-10-23 11:14  nameless_vi  阅读(117)  评论(0编辑  收藏  举报

导航