Java 中二分搜索的代码示例是怎样的

发布时间:2025-01-21 20:14:29 作者:小樊
来源:亿速云 阅读:97

在 Java 中,二分搜索(Binary Search)通常用于在一个已排序的数组中查找指定元素

public class BinarySearch {
    public static void main(String[] args) {
        int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15};
        int target = 7;

        int index = binarySearch(sortedArray, target);

        if (index != -1) {
            System.out.println("元素 " + target + " 在数组中的索引为: " + index);
        } else {
            System.out.println("元素 " + target + " 不在数组中");
        }
    }

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

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (sortedArray[mid] == target) {
                return mid;
            } else if (sortedArray[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1; // 如果找不到目标元素,返回 -1
    }
}

这个示例中,我们首先定义了一个已排序的整数数组 sortedArray 和一个目标值 target。然后,我们调用 binarySearch 方法来查找目标值在数组中的索引。如果找到目标值,binarySearch 方法返回其在数组中的索引;否则,返回 -1。

推荐阅读:
  1. JavaScript中二分查找法和计算重复次数的示例分析
  2. java 中二分法查找的应用实例

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

java

上一篇:Block Storage的容量规划和管理策略是什么

下一篇:如何在 Java 中处理大数据量的二分搜索

相关阅读

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

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