gpt4 book ai didi

c# - 二进制搜索算法 : Text File for each record in array

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

我有一个包含 90,000 个整数的数组,还有一个 txt 文件,我必须顺序读取txt文件并且不允许将它放入数组中,文本文件中的Foreach记录文件我必须使用二进制搜索在数组中找到相应的数字。然后显示有多少匹配数字。

我就是这样做的,但它只找到第一个匹配的数字然后停止

static void Main(string[] args)
{
//etc(OTHER CODE).......................
Array.Sort(NumFile);
// BINARY SEARCHHHH
int last,
first,
mid = 0,
target,
found = 0,
counter = 0;
string run;

//Stats
int Finds = 0;
first = 0;
last = NumFile.Length - 1;
//READ TextFile
StreamReader search = new StreamReader("Records.txt");
target = int.Parse(search.ReadLine());
//while (last >= first && found == 0)
while (last >= first && found == 0 && (run = search.ReadLine()) != null)
{
mid = (last + first) / 2;
if (target == NumFile[mid])
{
found = 1;
}
else
{
if (target < NumFile[mid])
{
last = mid - 1;
}
else
{
first = mid + 1;
}

}
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
}
else
{
//Console.WriteLine("\nNumber not found");
}

}

Console.WriteLine("Binary Search Statistics \t Hits:{0} ,hits);

} .

最佳答案

这是你的 while 循环,看看发现的 while 条件 == 0

while (last >= first && found == 0 && (run = search.ReadLine()) != null)
{
mid = (last + first) / 2;
if (target == NumFile[mid])
{
found = 1;
}
else
{
if (target < NumFile[mid])
{
last = mid - 1;
}
else
{
first = mid + 1;
}

}
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
}
else
{
//Console.WriteLine("\nNumber not found");
}

}

所以在 where found == 1 if 语句中你需要让 found 变为 = 0 以便它继续循环

if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
found =0;
}

关于c# - 二进制搜索算法 : Text File for each record in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464749/

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