好吧,我已经犯了同样的错误大约 18 个小时,我完全迷路了。我想要做的是进行二进制搜索,搜索从数组的中间开始,然后通过将搜索的术语与中间术语进行比较来每次消除数组的一半。到目前为止,我的代码没有产生错误,除非我尝试比较搜索项是否大于中间项。我知道我正在尝试比较两个字符串,因此大于不适用,但我不知道该怎么做。这是我的代码:
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)大于或小于?我认为因为它是排序的,所以它可能会比较第一个字母并据此确定,但我错了。
请您参考如下方法:
只需使用 List<T>.BinarySearch 方法。
List<String> myList = new List<String>{"Apple", "Microsoft", "Yahoo", "StackOverflow" };
myList.Sort(); //Apple Microsoft StackOverflow Yahoo
myList.BinarySearch("Yahoo"); // 3
或者如果使用 Array :
string[] myArr = new string[]{"Apple", "Microsoft", "Yahoo", "StackOverflow" };
Array.Sort(myArr); //Apple Microsoft StackOverflow Yahoo
Array.BinarySearch<string>(myArr, "Yahoo"); // 3
