1
我有一個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);
} .
我不明白你爲什麼要記住p在二進制搜索循環中讀取文件(進入「運行」)。它可能跳過整個文件,同時尋找第一個數字。我想你想要兩個嵌套循環:外部的文件讀取循環和內部的搜索循環。 – 2014-10-20 12:05:05
這是一個學校作業嗎?你爲什麼不直接調用[Array.BinarySearch](http://msdn.microsoft.com/en-us/library/2cy9f6wb(v = vs.110).aspx)? – 2014-10-20 12:51:18