gpt4 book ai didi

c# - 如何在二维数组中应用二进制搜索?

转载 作者:行者123 更新时间:2023-11-30 22:52:21 25 4
gpt4 key购买 nike

我必须通过二进制搜索从数组中搜索姓名,但显示的是该人姓名的相应年龄。请不要提出其他建议,我必须使用二维数组的二进制搜索来完成。

string[,] persons = new string[4, 2];
persons[0, 0] = "Ana";
persons[0, 1] = "19";
persons[1, 0] = "Ammara";
persons[1, 1] = "20";
persons[2, 0] = "Marilyn";
persons[2, 1] = "40";
persons[3, 0] = "Zacharaia";
persons[3, 1] = "70";
string x = "Zacharia";
int upBound = persons.GetLength(0) - 1;
int lowBound = 0;
while (lowBound <= upBound)
{
int midpoint = lowBound + (upBound - lowBound) / 2;
int result = x.CompareTo(persons[midpoint, 1]);
if (result == midpoint)
{
Console.WriteLine("The value is present at:" + persons[midpoint, 1]);
break;
}
else if (result > midpoint)
{
lowBound = midpoint + 1;
Console.WriteLine("The value is present at:" + persons[lowBound, 1]);
break;
}
else if (result < midpoint)
{
upBound = midpoint - 1;
Console.WriteLine("The value is present at:" + persons[upBound, 1]);
break;
}
}

此代码显示每个人的年龄为 20。CompareTo() 方法无效。

最佳答案

你的代码有 4 个主要问题:

1- 使用 midpoint2 , lowBound2upBound2由于不明原因,您应该使用 01相反。

2- 由于您依赖二分查找,因此必须对关键元素进行排序,因此“Ana”必须在“Ammara”之后,尽管她更年轻,但您搜索的是名字而不是年龄,或者将其更改为另一个名字,例如“阿卡”。

3- result应该与 0 进行比较, < 0> 0 ,与midpoint无关.

4- 你应该使用 Console.WriteLinebreak在第一个条件下只让 while如果尚未找到该名称,则继续。

string[,] persons = new string[4, 2];
persons[0, 0] = "Aca";
persons[0, 1] = "19";
persons[1, 0] = "Ammara";
persons[1, 1] = "20";
persons[2, 0] = "Marilyn";
persons[2, 1] = "40";
persons[3, 0] = "Zach";
persons[3, 1] = "70";
string x = "Aca";
int upBound = persons.GetLength(0) - 1;
int lowBound = 0;
while (lowBound <= upBound)
{
int midpoint = lowBound + (upBound - lowBound) / 2;
int result = x.CompareTo(persons[midpoint, 0]);
if (result == 0)
{
Console.WriteLine("The value is present at:" + persons[midpoint, 1]);
break;
}
else if (result > 0)
{
lowBound = midpoint + 1;
}
else
{
upBound = midpoint - 1;
}
}

关于c# - 如何在二维数组中应用二进制搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com