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)
);