开发者社区> 问答> 正文

java二分法查找的递归算法怎么实现

java二分法查找的递归算法怎么实现

展开
收起
知与谁同 2018-07-22 20:04:30 2141 0
3 条回答
写回答
取消 提交回答
  • public class Solution {
        public int binarySearch(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            return helper(nums, target, 0, nums.length-1);
        }
        private int helper(int[] nums, int target, int start, int end) {
            if (start>end) {
                return -1;
            }
            int mid = start + (end-start)/2;
            if (nums[mid] == target) {
                return mid;
            } if (nums[mid] < target) {
                return helper(nums, target, mid+1, end);
            } else {
                return helper(nums, target, start, mid-1);
            }
        }
    }
    
    2019-07-17 22:54:54
    赞同 1 展开评论 打赏
  • 主要是先找到递归的截止条件
    2019-07-17 22:54:54
    赞同 展开评论 打赏
  • 杀人者,打虎武松也。
    public class 二分法递归查找 {
    public static void main(String[] args) {

    //定义数组,注意,二分查找数组必须是有序的数组!
    int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15, 17 };

    //接受查找后的返回值:索引值,如果没有则是-1;
    //测试查找元素:9
     int a=binary(arr, 9, 0, arr.length - 1);
    System.out.println("被查找数字索引位置在:"+a);
    }
    //参数列表依次为:被查找的数组,查找的数字,头索引,尾索引!
    public static int binary(int[] arr, int key, int star, int end)// 递归
    {
    //每次进来创建,中间索引值!
    int mid = (star + end) / 2;
    //如果被查找数小于头,或者尾,或者头索引大于尾索引,则说明无该数,返回-1;
    if (key < arr[star] || key > arr[end] || star > end) {
    return -1;
    }
    //如果中间值小于被查找数,则重新定义头索引移至中间+1位置,筛选掉一半数字!
    if (arr[mid] < key) {
    //开始递归!
    return binary(arr, key, mid + 1, end);
    //否则如果中间值大于被查找数,则重新尾索引移至中间-1位置,筛选掉一半数字!
    } else if (arr[mid] > key) {
    //开始递归!
    return binary(arr,key, star, mid - 1);
    } else {
    //否者就是找到了,返回该索引!
    return mid;
    }
    }
    }

    2019-07-17 22:54:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载