我的二分搜索只会找到位于数组中间的元素
所以我试图进行二分搜索来按姓氏查找,但我的代码只会查找我搜索的元素是否位于数组中间的元素,否则它将冻结并崩溃,有人知道我在做什么吗?做错了吗?谢谢。
private int binarySearch(string surnameSearched)
{
int start = 0;
int end = direcTable.Length - 1;
bool found = false;
bool allListSearched = false;
int mid = (start + end) / 2;
while ((!found) && (!allListSearched))
{
lvDirectory.Items.Clear();
if (String.Compare(direcTable[mid].surname, surnameSearched, true) == 0)
{
found = true;
}
else if (start > end)
{
allListSearched = true;
}
else if (String.Compare(direcTable[mid].surname, surnameSearched) < 0)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
if (found)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = direcTable[mid].extCode;
lvi.SubItems.Add(direcTable[mid].forename);
lvi.SubItems.Add(direcTable[mid].surname);
lvDirectory.Items.Add(lvi);
return (mid);
}
else
{
return -1;
}
So I'm trying to make a binary search to find out by the surname but my code will only find if the element I search is the one located in the middle of the arrays, otherwise it will freeze and crash, does anyone knows what I'm doing wrong? Thank you.
private int binarySearch(string surnameSearched)
{
int start = 0;
int end = direcTable.Length - 1;
bool found = false;
bool allListSearched = false;
int mid = (start + end) / 2;
while ((!found) && (!allListSearched))
{
lvDirectory.Items.Clear();
if (String.Compare(direcTable[mid].surname, surnameSearched, true) == 0)
{
found = true;
}
else if (start > end)
{
allListSearched = true;
}
else if (String.Compare(direcTable[mid].surname, surnameSearched) < 0)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
if (found)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = direcTable[mid].extCode;
lvi.SubItems.Add(direcTable[mid].forename);
lvi.SubItems.Add(direcTable[mid].surname);
lvDirectory.Items.Add(lvi);
return (mid);
}
else
{
return -1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)