好吧,所以我一直在这个相同的错误大约18个小时,我完全失去了。我试图做的是进行二进制搜索,搜索从数组中间开始,然后每次将搜索到的术语与中期术语进行比较,从而消除数组的一半。到目前为止,我的代码不会产生错误,除非我试图比较搜索到的术语是否大于中间术语。我知道我试图比较两个字符串,并且比不适用更大,但我不知道如何去做。这里是我的代码:在C中的数组中的字符串的二进制搜索#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
string[] contacts = new string[20];
private void button1_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear(); //Clears the ListBox of all previous items
if (!File.Exists("Week3List.txt")) //Verifies that the file exists
{
MessageBox.Show("You need to write the file first", "Validation", MessageBoxButton.OK); //Notifies the user if the file does not exist
return;
}
using (StreamReader sr = new StreamReader("Week3List.txt")) //Designates the path to the file that was created
{
try
{
contacts = File.ReadAllLines("Week3List.txt");
Array.Sort(contacts);
foreach (string contact in contacts)
{
listBox1.Items.Add(contact);
}
sr.Close(); //Closes the StreamReader
}
catch (Exception ex) //A catch to handle access errors
{
MessageBox.Show(ex.ToString(), "Exception Handler", MessageBoxButton.OK); //Adds the error message to the ListBox
}
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
bSearch(contacts);
}
private void bSearch(string[] contacts)
{
int index = Array.BinarySearch(contacts, textBox1.Text);
}
public int BinarySearch(string[] contacts, string searchTerm)
{
int first = 0;
int last = contacts.Length - 1;
int position = -1;
bool found = false;
int compCount = 0;
searchTerm = textBox1.Text;
while (found != true && first <= last)
{
int middle = (first + last)/2;
if (contacts[middle] == searchTerm)
{
found = true;
position = middle;
compCount++;
MessageBox.Show("Your search has been found after " + compCount + "comparisons.");
}
else if (contacts[middle] > searchTerm)
{
last = middle;
compCount++;
}
else
{
first = middle;
compCount++;
}
}
return position;
return compCount;
}
}
}
有谁看到我错了或不知道的方式来比较两个一大于value还是少了?我以为是因为它被排序,它可能会比较第一个字母,并根据这个决定,但我错了。
你在做20项二元搜索吗?或者这只是一个例子,项目的数量要大得多? – Enigmativity 2014-09-30 05:12:20
2'return'指令不断??真? – 2014-09-30 05:20:53
二进制搜索是从文本文件中读取的20个名称。至于2'return'指令不断评论,我不确定你的意思。我打了一个连续的“退货”,我错过了吗? – 2014-09-30 05:27:01