二分法查找递归方式()

二分法,前提数据是有序的:

 1 package day04;
 2 public class test9 {
 3     public static void main(String[] args) {
 4         // 3.使用二分法查找有序数组中元素。找到返回索引,不存在输出-1。使用递归实现
 5 
 6         int[] nums = { 1, 2, 3, 4, 5, 6, 7, 9,90 };
 7         System.out.println(erfen(nums, 60, 0, nums.length-1));
 8 
 9     }
10 
11     /**
12      * 二分法查找(递归)
13      * @param nums 要查找的数组
14      * @param m 要查找的值
15      * @param left 左边最小值
16      * @param right 右边最大值
17      * @return 返回值 成功返回索引,失败返回-1
18      */
19     public static int erfen(int[] nums, int m, int left, int right) {
20         int midIndex = (left + right) / 2;
21         //因为是二分法查找要求有序数组,所以超出数组边界的肯定都是查找不到的,左边小于右边也是不能查找的
22         if (m < nums[left] || m > nums[right] || nums[left] > nums[right]) {
23             return -1;
24         }
25         //找中间值
26         int midValue = nums[midIndex];
27         if (midValue == m) {
28             return midIndex;
29         } else if (midValue > m) {
30             //如果中间值大于要找的值则从左边一半继续递归
31             return erfen(nums, m, left, midIndex);
32         } else {
33             //如果中间值小于要找的值则从右边一半继续递归
34             return erfen(nums, m, midIndex, right);
35         }
36 
37     }
38 }
原文地址:https://www.cnblogs.com/xujingyang/p/6480348.html