微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这个二分搜索有什么问题?索引出界

如何解决这个二分搜索有什么问题?索引出界

我正在尝试编写二进制搜索算法,但是 Geeks for Geeks practice problem Binary Search 产生以下错误

Runtime Error:
Runtime ErrorException in thread "main" java.lang.Arrayindexoutofboundsexception: 

  Index 222 out of bounds for length 5

    at Solution.binarysearch(GFG.java:44)
    at GFG.main(GFG.java:22)

到目前为止我写的是,

class Solution {
    int binarysearch(int arr[],int n,int k){
        
        if (arr == null) return -1;
        
        int begin = 0;
        int end = k;

            for (; begin < end;)
            {
                int mid = (begin + end) / 2;
                if (arr[mid] == n) return mid;
                if (arr[mid] > n)
                {
                    // in left part
                    begin = begin;  // for debug
                    end = mid; 
                }
                else
                {
                    // in right part
                    begin = mid + 1;
                    end = end; // for debug
                }
            }

            return -1;
    }
}

Geeks for Geeks问题陈述&示例:

给定一个大小为 N 的排序数组和一个整数 K,找到在 使用二进制搜索,数组中存在哪个 K。

示例 1

输入:N = 5 arr[] = {1 2 3 4 5} K = 4
输出:3
说明:4 出现在索引 3 处。

解决方法

int end = k; 替换为 int end = n-1;

k 是您要查找的数字,n 是数组大小

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?