c# - 二进制搜索算法 : Text File for each record in array

标签 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);        

}    .

最佳答案

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

关于c# - 二进制搜索算法 : Text File for each record in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464749/

相关文章:

c# - 仅返回字符串中的数字 0-9

arrays - 如何使我的 ruby​​ remove_duplicates(nums) 算法更高效

c - C 字符串中 '0' 、 0 和 '\0' 之间的区别

algorithm - Chaitin-Briggs 算法解释

algorithm - 从抛硬币创建随机数生成器

javascript - 避免重复计算优化嵌套for循环的时间复杂度

c# - 智能卡读卡器命名

c# - 将背景图像添加到 asp.net 主网页 asp.net 4.0 和 html5

c# - 在 Windows 中以编程方式确认成功打印

使用 memcpy 将数组复制到新数组