二进制搜索算法:数组中每个记录的文本文件

本文关键字:记录 文本 文件 搜索算法 数组 二进制 | 更新日期: 2023-09-27 18:27:05

我有一个包含90000个整数的数组,还有一个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 find==1内部,如果您需要使语句find to=0,那么它将在循环中继续

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