如何解决这个二分搜索有什么问题?索引出界
我正在尝试编写二进制搜索算法,但是 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 举报,一经查实,本站将立刻删除。