gpt4 book ai didi

c# - 二进制搜索算法随机生成的数组项不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:55 26 4
gpt4 key购买 nike

我已经在 C# 的控制台窗口应用程序中实现了二进制搜索算法。我正在为数组生成随机值,并分别使用 Random()Array.Sort() 函数对它们进行排序。

问题 - 无论我给出什么Key(要在数组中搜索的项目),程序都会返回 未找到键当使用随机函数生成数组项时

如果我使用 Console.ReadLine() 手动输入数组元素,则不会发生这种情况。

TLDR:当手动输入数组项时,二进制搜索算法工作正常,但当使用 Random 函数生成数组项时,不起作用 .

谁能指出我做错了什么?

我的代码 - 随机生成的数组项。

namespace BSA
{
class Program
{
static void Main(string[] args)
{
var arr = new int[10];

Random rnd = new Random();

for (int i = 0; i < arr.Length; i++)
{
arr[i] = rnd.Next(1, 1000);
}

Array.Sort(arr);

for (int i = 0; i < arr.Length; i++)
{
Console.Write("{0}\n", i);
}

while (true)
{
Console.WriteLine("Enter the number to be searched in the array.");

var searchItem = Convert.ToInt32(Console.ReadLine());

var foundPos = Search(arr, searchItem);

if (foundPos > 0)
{
Console.WriteLine("Key {0} found at position {1}", searchItem, foundPos);
}
else
{
Console.WriteLine("Key {0} not found", searchItem);
}
}
}

public static int Search(int[] arr, int item)
{
var min = 0;
var N = arr.Length;
var max = N - 1;
int basicOperations = 0;

basicOperations++;
do
{
var mid = (min + max)/2;

if (arr[mid] == item)
return mid;

if (item < arr[mid])
max = mid - 1;
else
min = mid + 1;

basicOperations++;
} while (min <= max);

return basicOperations;
}
}
}

如果我犯了任何愚蠢的错误或者我在上面的代码中犯了错误,请告诉我。任何帮助都会非常有帮助。

最佳答案

据我所知,您的搜索代码运行良好。但是,当您列出随机数组的内容时,您应该编写 arr[i] 而不是 i 来查看数组中的内容,以便您可以在其中选择一个搜索值.或者,传递 arr[x] 作为搜索项。它应该返回 x

关于c# - 二进制搜索算法随机生成的数组项不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234109/

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