Array.BinarySearch does not find item using IComparable

Posted by Sir Psycho on Stack Overflow See other posts from Stack Overflow or by Sir Psycho
Published on 2010-05-29T04:21:04Z Indexed on 2010/05/29 4:32 UTC
Read the original article Hit count: 281

Filed under:
|
|

If a binary search requires an array to be sorted before hand, why does the following code work?

string[] strings = new[] { "z", "a", "y", "e", "v", "u" };
int pos = Array.BinarySearch(strings, "Y", StringComparer.OrdinalIgnoreCase);           
Console.WriteLine(pos);

And why does this code result return -1?

 public class Person : IComparable<Person> {

    public string Name { get; set; }
    public int Age { get; set; }


    public int CompareTo(Person other) {
        return this.Age.CompareTo(other.Age) + this.Name.CompareTo(other.Name);
    }
}
var people = new[] {

                new Person { Age=5,Name="Tom"},
                new Person { Age=1,Name="Tom"},
                new Person { Age=2,Name="Tom"},
                new Person { Age=1,Name="John"},
                new Person { Age=1,Name="Bob"},
            };


            var s = new Person { Age = 1, Name = "Tom" };

            // returns -1
            Console.WriteLine(
                Array.BinarySearch(people, s)
            );

© Stack Overflow or respective owner

Related posts about c#

Related posts about array