已排序数组的二分查找
我正在尝试使用此二进制搜索代码搜索降序排序的数组。然而,在我对它进行排序并尝试搜索之后,它没有返回任何结果,只是一个加载图标,它永远不会消失,就好像它有一个无限循环一样。我不确定问题是什么,因为代码看起来合乎逻辑。
这是4.0框架的aspx,c#。提前致谢!
protected void Button2_Click(object sender, EventArgs e)
{
String item = TextBox1.Text;
int target = Convert.ToInt16(item);
int mid, first = 0, last = mynumbers.Length - 1;
//for a sorted array with descending values
while (first<=last)
{
mid = (first + last) / 2;
if (target < mynumbers[mid])
first = mid + 1;
if (target > mynumbers[mid])
last = mid - 1;
else
Label11.Text = "Target " + item + " was found at index " + mynumbers[mid];
}
I am trying to search a descending sorted array using this binary search code. However, after I sort it, and try to search, it doesn't come back with any result, just a loading icon that never goes away as if it has an infinite loop. I'm not sure what the problem is because the code looks logical.
This is aspx with 4.0 framework, c#. Thanks in advance!
protected void Button2_Click(object sender, EventArgs e)
{
String item = TextBox1.Text;
int target = Convert.ToInt16(item);
int mid, first = 0, last = mynumbers.Length - 1;
//for a sorted array with descending values
while (first<=last)
{
mid = (first + last) / 2;
if (target < mynumbers[mid])
first = mid + 1;
if (target > mynumbers[mid])
last = mid - 1;
else
Label11.Text = "Target " + item + " was found at index " + mynumbers[mid];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Array
类中有一个二分搜索:对于降序排列,可以使用
ReverseComparer
轻松完成,它很容易编写如下:那么:
如果这是一个学术问题练习时,您必须使用自定义搜索,当然,这不适用。如果它必须是类的自定义算法,那么问题是您必须在找到时跳出循环,并且索引位于
mid
,而不是mynumbers[mid]
:实际上,我可能会设置一个 bool 标志来保持算法的纯粹性,而不是将查找与输出问题混合在一起,这也将使您更容易知道如果退出循环而未找到会发生什么:
There is a binary search in the
Array
class:For descending order, this can be easily accomplished with a
ReverseComparer
which is easy to write like:Then:
If this is an academic exercise and you must use a custom search, of course, this won't apply. If it's got to be a custom algorithm for a class, then the problems are that you must break out of the loop when found, and the index is at
mid
, not atmynumbers[mid]
:And actually, I'd probably set a bool flag instead to keep the algorithm pure and not mix the find with the output concerns, this will also make it easier to tell what happened if you exit the loop with not found:
在黑暗中拍摄:
我怀疑你在 mid+1 和 mid-1 之间来回跳动
Shot in the dark:
I suspect you're bouncing back and forth between mid+1 and mid-1
这是一个正确的:
This is one correct :
它对我有用
Its worked for me
在
.NET 8
中使用C# 12
进行二分搜索。使用
NUnit 3
进行测试。Binary search using
C# 12
in.NET 8
.Tested using
NUnit 3
.