二进制搜索算法:数组中每条记录的文本文件
Posted
技术标签:
【中文标题】二进制搜索算法:数组中每条记录的文本文件【英文标题】:Binary Search Algorithm: Text File for each record in array 【发布时间】:2014-12-15 09:10:28 【问题描述】:我有一个包含 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);
.
【问题讨论】:
我不明白您为什么在二进制搜索循环中继续读取文件(进入“运行”)。它可能在寻找第一个数字时跳过了整个文件。我认为您需要两个嵌套循环:外部文件读取循环和内部搜索循环。 这是学校作业吗?你为什么不直接打电话给Array.BinarySearch? 【参考方案1】:这是您的 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;
【讨论】:
以上是关于二进制搜索算法:数组中每条记录的文本文件的主要内容,如果未能解决你的问题,请参考以下文章