这种二分搜索适用于所有字符串,除了带有空格的字符串。NameBox.Text 是提供搜索输入的地方。关键是在 Namebox 中搜索一个标题,并在“Game”中读取它,这是一个字符串列表框,然后如果找到了游戏,则使用游戏数据填充 NameBox、PlatformBox 和 CostBox 字段。
private void BinarySearch_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(NameBox.Text))
{
log.Items.Clear();
log.Items.Add("Please enter a string");
return;
}
int min = 0;
int max = Game.Length - 1;
string search = NameBox.Text;
while (min <= max)
{
int mid = (min + max) / 2;
if (Game[mid] == search)
{
log.Items.Clear();
log.Items.Add("Game " + Game[mid] + " found!");
NameBox.Text = Game[mid];
PlatformBox.Text = Platform[mid];
String cost1 = Cost[mid].ToString("$0.00");
CostBox.Text = cost1;
NameBox.Focus();
return;
}
else if (Game[mid] != search)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
log.Items.Clear();
log.Items.Add("Game not found");
NameBox.Focus();
}