我创建了一个同时使用线性和二分查找方法的程序。我使用字符串数组。
private void linearSearch_Click(object sender, EventArgs e)
{
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
这是可行的,但是二进制文件不可行
private void BinarySearch_Click(object sender, EventArgs e)
{
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if(numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target+ " is at index: " + numIndex;
}
}
1条答案
按热度按时间w6lpcovy1#
请注意,程式码是在binarySearchBox的文字方块中执行二进制搜寻,而不是ListBox1文字方块中的值。
需要将添加到ListBox1的值转换为Array数组以进行存储的代码。
string[]myArray = listBox1.Items.Cast<string>().ToArray();
,然后搜索ListBox1。代码显示如下: