我第一次使用二进制搜索数组并遇到麻烦。我很确定问题出在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);
}
}
答案 0 :(得分:0)
你的数组初始化程序有一堆字符串,前面有空格。您的搜索字符串没有空格,因此无法找到。
&LT;咆哮&GT; 如果您没有包含所有其他的数组操作,这将更容易回答。将问题减少到重现错误所需的最小代码集总是一个好主意,因为这样做通常可以帮助您确定问题实际存在的位置。 &LT; /咆哮&GT;
抱歉,不得不放弃我的胸膛:P