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

时间:2014-09-30 05:07:56

标签: c# arrays

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

有没有人知道我哪里出错了,或者知道如何比较两者的价值是大于还是小于?我想是因为它的排序可能会比较第一个字母并确定基于此但我错了。

5 个答案:

答案 0 :(得分:3)

只需使用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

答案 1 :(得分:1)

好的,感谢RegularExpression提供了查看比较字符串的方法的建议。我改变了代码

if (contacts[middle] == searchTerm)else if (contacts[middle] > searchTerm)

if (string.Compare(contacts[middle], searchTerm, true) == 0)else if (string.Compare(contacts[middle], searchTerm, true) > 0)

现在它完美无缺!谢谢大家的快速回复。

答案 2 :(得分:0)

嗯,你试过了吗?

contacts.ToList().BinarySearch(searchTerm);

答案 3 :(得分:0)

请查看此方法以比较字符串。它将告诉您字符串是否大于,小于或等于(值)另一个字符串:

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

答案 4 :(得分:0)

如果你想对字符串数组进行二进制搜索,这就是这样做的方法。您可能希望为StringComparer选择不同的Culture。

string[] arr = {"a","b","c","d","e","f","g"};

int k = Array.BinarySearch(arr,"d",StringComparer.InvariantCulture);