在C#中对数组中的字符串进行二进制搜索

卡梅隆·布里格斯(Cameron Briggs)

好的,所以我在同一错误中出现了大约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;
    }
}
}

是否有人看到我要去哪里错了,还是知道一种比较两者的方法,以得出大于或小于值的值?我认为是因为对它进行排序后,它可能会比较第一个字母并根据该字母来确定,但我错了。

正则表达式

看一下比较字符串的方法。它会告诉您一个字符串是大于,小于还是等于另一个字符串:

http://msdn.microsoft.com/zh-cn/library/zkcaxw5y%28v=vs.110%29.aspx

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章