2014-03-01 26 views
0

我只是關於Array.BinarySearch()的一個小問題,以及關於這個方法以某種方式看不到或無法識別的信件。Array.BinarySearch()和丟失的字母

我創建了一個基本陣列來嘗試這個方法我剛纔遇到:

 string[] Letters1 = { "q", "j", "i", "o" }; 
     int index1 = Array.BinarySearch(Letters1, "q"); 
     Console.WriteLine(index1); 
     Console.ReadKey(); 
     string[] Letters2 = { "i", "q", "o", "a" }; 
     int index2 = Array.BinarySearch(Letters2, "q"); 
     Console.WriteLine(index2); 
     Console.ReadKey(); 

不知何時開始改變它開始給錯誤的結果 像在上述情況中的字母和它們的位置。 ..當我有第一個陣列中的第一個位置q和結果-5和下一個數組中顯示正確。

+0

你'Letters1'和'Letters2'數組不能有序,所以二分查找會給不可預知的結果。如果您在調用BinarySearch之前調用'Array.Sort(Letters1)'和'Array.Sort(Letters2)',您將獲得可預測的結果。 –

回答

3

二進制搜索僅適用於訂購集合。

Array.BinarySearch:搜索的一維排序陣列爲一個值,使用二進制搜索算法。