温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java二分搜索如何编写递归版本

发布时间:2025-07-20 15:11:14 来源:亿速云 阅读:103 作者:小樊 栏目:编程语言

在Java中,编写一个递归版本的二分搜索算法需要遵循以下步骤:

  1. 定义一个递归方法,传入数组、目标值、搜索范围的起始和结束索引。
  2. 计算中间索引。
  3. 检查中间元素是否等于目标值。如果是,则返回中间索引。
  4. 如果目标值小于中间元素,则在左半部分继续搜索;如果目标值大于中间元素,则在右半部分继续搜索。
  5. 递归调用方法,更新搜索范围的起始或结束索引。
  6. 如果搜索范围无效(起始索引大于结束索引),则返回-1表示未找到目标值。

以下是一个递归版本的二分搜索算法的Java实现:

public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13};
        int target = 7;
        int result = binarySearch(arr, target, 0, arr.length - 1);
        System.out.println("Target found at index: " + result);
    }

    public static int binarySearch(int[] arr, int target, int start, int end) {
        if (start > end) {
            return -1; // Target not found
        }

        int mid = start + (end - start) / 2;

        if (arr[mid] == target) {
            return mid; // Target found
        } else if (target < arr[mid]) {
            return binarySearch(arr, target, start, mid - 1); // Search in the left half
        } else {
            return binarySearch(arr, target, mid + 1, end); // Search in the right half
        }
    }
}

这个实现中,binarySearch方法是一个递归方法,它接受一个整数数组arr、目标值target以及搜索范围的起始索引start和结束索引end。如果找到目标值,该方法将返回其在数组中的索引;否则,返回-1。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手