作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚开始学习Java(这是我第一次用Java 编程)。在 print 语句所在的位置(纯粹用于测试目的),代码会重复输出 mid 而不会更改它。我想了好几个小时,还是想不出来。帮助将不胜感激。
/*class containing binary search algorithm*/
public class BinarySearch {
/*conducts a binary search as specified by user*/
public static int binarySearch(int queryValue, int[] list) {
int length = list.length;
/*last point of list*/
int top = length-1;
/*first point of list*/
int bottom = 0;
/*starting midpoint of list*/
int mid = (int)Math.round((top + bottom)/2);
/*binary search*/
while(bottom < top) {
if((int)queryValue == (int)list[mid]) {
return mid;
}
else if(queryValue > list[mid]) {
bottom = mid;
mid = (int)Math.round((top + bottom) / 2);
StdOut.print(mid);
}
else {
top = mid;
mid = (top + bottom) / 2;
}
}
/*returns -1 if user value not found*/
return -1;
}
}
最佳答案
如果您的值大于中点,则中点将被消除。将 bottom
前进到当前 mid
之后:
bottom = mid + 1;
类似地,对于小于中点的情况,将 top
在当前 mid
之前前进:
top = mid - 1;
否则,您可能会遇到 bottom
和 top
永远不会相互交叉的情况。
此外,二分搜索仅在输入已排序时才有效。请确认/确保您的数组已排序。
关于java - 我的二分查找出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345089/
我正在尝试编写一个程序,在名为 items 的数组中进行顺序搜索和二分搜索,该数组具有 10000 个已排序的随机 int 值。第二个名为 targets 的数组加载了 1000 个 int 值(50
当我尝试使用图表并为其编写一些代码但没有成功时,我遇到了一个问题:/!! 我想创建一些东西来获取图形数据并检查它是否:1- 连接2-二分法3-有循环4-是一棵树 所以我想知道,例如,是否可以将其写入以
我是一名优秀的程序员,十分优秀!