C# 二进制搜索算法:数组中每个记录的文本文件
我有一个包含90000个整数的数组,还有一个txt文件, 我必须按顺序读取txt文件,并且不允许将其放入数组中,即文本文件中的每条记录 我必须使用二进制搜索在数组中找到相应的数字。然后显示匹配的数字数量 我就是这样做的,但它只找到第一个匹配的号码,然后停止C# 二进制搜索算法:数组中每个记录的文本文件,c#,arrays,algorithm,text,binary,C#,Arrays,Algorithm,Text,Binary,我有一个包含90000个整数的数组,还有一个txt文件, 我必须按顺序读取txt文件,并且不允许将其放入数组中,即文本文件中的每条记录 我必须使用二进制搜索在数组中找到相应的数字。然后显示匹配的数字数量 我就是这样做的,但它只找到第一个匹配的号码,然后停止 static void Main(string[] args) { //etc(OTHER CODE)....................... Array.Sort(NumFile); // BINARY SEA
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条件find==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");
}
}
我不明白你为什么一直在二进制搜索循环中读取文件。它可能在查找第一个数字时跳过了整个文件。我想你需要两个嵌套的循环:外部的文件读取循环和内部的搜索循环。这是学校作业吗?你为什么不打个电话呢?
if (found == 1)
{
Console.WriteLine("\nThe number was found at location {0}", mid);
Finds++;
found =0;
}