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

时间:2014-10-20 11:36:31

标签: c# arrays algorithm text binary

我有一个包含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);        

}    .

1 个答案:

答案 0 :(得分:0)

这是你的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");                  
    }

}

所以在里面找到== 1 if语句你需要找到= 0所以它继续循环

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