Java二分搜索如何确定中间元素

发布时间:2026-01-01 06:33:35 作者:小樊
来源:亿速云 阅读:88

在Java中,使用二分搜索时,确定中间元素的方法是:(left + right) / 2。这里,left和right分别表示数组的起始索引和结束索引。

以下是一个简单的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);
        if (result != -1) {
            System.out.println("Element found at index: " + result);
        } else {
            System.out.println("Element not found in the array");
        }
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2; // 计算中间元素的索引

            if (arr[mid] == target) {
                return mid; // 找到目标元素,返回索引
            } else if (arr[mid] < target) {
                left = mid + 1; // 目标元素在右侧子数组中
            } else {
                right = mid - 1; // 目标元素在左侧子数组中
            }
        }

        return -1; // 没有找到目标元素
    }
}

在这个例子中,我们使用left + (right - left) / 2来计算中间元素的索引,这样可以避免直接相加可能导致的整数溢出问题。

推荐阅读:
  1. Java创建或修改权限的方法是什么
  2. Java中怎么实现类隔离加载?

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

java

上一篇:Ansible与云服务如何结合使用

相关阅读

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

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