Emm*_*ley 9 c# arrays binary-search
我正在尝试使用此二进制搜索代码搜索降序排序数组.然而,在我对它进行排序并尝试搜索之后,它不会带来任何结果,只是一个永远不会消失的加载图标就好像它有一个无限循环.我不确定问题是什么,因为代码看起来合乎逻辑.
这是带有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];
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*are 20
在Array课堂上有二进制搜索:
int index = Array.BinarySearch(mynumbers, target);
Run Code Online (Sandbox Code Playgroud)
对于降序,这可以很容易地完成,ReverseComparer如下所示:
public class ReverseComparer<T> : IComparer<T>
{
public int Compare(T x, T y)
{
return Comparer<T>.Default.Compare(y, x);
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
int index = Array.BinarySearch(numbers, 7, new ReverseComparer<int>());
Run Code Online (Sandbox Code Playgroud)
如果这是学术练习,您必须使用自定义搜索,当然,这不适用.如果它必须是一个类的自定义算法,那么问题是你必须在找到时突破循环,并且索引位于mid,而不是mynumbers[mid]:
//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
{
// the index is mid, not mynumbers[mid], and you need to break here
// once found or it's an infinite loop once it finds it.
Label11.Text = "Target " + item + " was found at index " + mid;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,我可能会设置一个bool标志来保持算法的纯净,而不是将find与输出问题混合在一起,这也可以让你更容易分辨出如果你没有找到它就退出循环:
bool found = false;
//for a sorted array with descending values
while (!found && first<=last)
{
mid = (first + last) / 2;
if (target < mynumbers[mid])
{
first = mid + 1;
}
if (target > mynumbers[mid])
{
last = mid - 1;
}
else
{
// You need to stop here once found or it's an infinite loop once it finds it.
found = true;
}
}
Label11.Text = found
? "Item " + item + " was found at position " + mid
: "Item " + item + " was not found";
Run Code Online (Sandbox Code Playgroud)