如果二进制搜索需要事先对数组进行排序,为什么下面的代码可以工作?
string[] strings = new[] { "z", "a", "y", "e", "v", "u" };
int pos = Array.BinarySearch(strings, "Y", StringComparer.OrdinalIgnoreCase);
Console.WriteLine(pos);为什么这个代码结果返回-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)
);发布于 2010-05-29 12:23:40
如果违反了the pre-condition (“数组中的元素必须已经按照比较器定义的排序顺序按升序排序;否则,结果可能是不正确的。”),您会导致未定义的行为,有时会包括,“嘿,看起来像是起作用了。”在释放后使用和许多其他编程错误也是如此。
我对此并不感到惊讶,因为"y“和"e”都是同样的中间元素。它使用中间较低的"y",这是匹配的。如果你尝试:
string[] strings = new[] { "z", "a", "y", "e", "e", "v", "u" };你会发现这是行不通的。请注意,元素的数量是奇数。目标在中间之前,而它应该在中间之后。
https://stackoverflow.com/questions/2933785
复制相似问题