我第一次使用二進制搜索數組並遇到麻煩。我很確定這個問題在void FindMyObject中。有任何想法嗎?二進制部分接近底部。它被標記。它沒有錯誤地運行,所以我相信我很接近。我已經看過幾個例子,看起來這樣,我還沒有100%的理解邏輯。有什麼建議?二進制搜索數組對象
string[] myStrArray = new string[] { " I"," am"," a"," Stella"," Student" };
object[] myObjArray = new object[] { " You"," are"," a"," Great"," Learner" };
void Page_Load(object sender, EventArgs e)
{
//Binary Search Array
Array.Sort(myStrArray);
Array.Sort(myObjArray);
Response.Write("<br/><br/>");
PrintValues(myStrArray);
PrintValues(myObjArray);
object myStr = "Learner";
FindMyObject(myStrArray, myStr);
object myObj = "Stella";
FindMyObject(myObjArray, myObj);
}
void FindMyObject(Object[] myArr, object myObject)
{
int myIndex = Array.BinarySearch(myArr, myObject);
if (myIndex < 0)
{
Console.WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, myIndex);
}
else
{
Console.WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex);
}
}
我相信你不小心換成myStr的和MyObj中的分配。 – Carth
myObjArray必須排序 – evhen14
@ evhen14他調用Array.Sort來對數組進行排序。 – Corey