首页 > 解决方案 > C#二分查找不返回结果

问题描述

代码:

using System;
using System.IO;
using System.Collections.Generic;

class MainClass {
    public static void Main (string[] args) {
        Console.WriteLine ("Get Random Names");
        // Read every line in the file.
        List<string> nameList = new List<string>();
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
        {
            nameList.Add(line);
        }
    }

        nameList.Sort();
        int startValue = 0;
        int middleValue = (nameList.Count + 1) / 2;
        int endValue = (nameList.Count + 1);

        Console.WriteLine("Enter a name to search for.");
        String name = Console.ReadLine();

        bool nameNotFound = true;
        var compareResult = String.Compare(nameList[middleValue], name);


        while (nameNotFound) { 
            if (compareResult < 0) {
              endValue = middleValue;
              middleValue = endValue / 2;
            }
            else if (compareResult > 0) {
              startValue = middleValue;
              middleValue = (endValue - startValue) / 2 + startValue;
            }
            else {
              Console.WriteLine("Name " + name + " was found.");
              nameNotFound = false;
            }
        }
}
}

问题:我正在尝试编写一个 C# 二进制搜索来搜索具有列表名称(字符串)的文件。由于某种原因,我无法弄清楚,搜索没有返回任何结果。有人有想法么?

解决方案:我现在已经修复了代码。这两个问题是我没有比较 if 和 else if 循环中的值,而且我的大于和小于符号混淆了。

标签: c#binary-search

解决方案


在最后的主算法循环中,您永远不会重新计算compareResult,因此您的程序无法判断它何时找到了某些东西。

您需要compareResult = String.compare ...ifandelse if块中添加一个。.

如果您不这样做,compareResult将保留您在循环之前进行的第一次比较的结果。


推荐阅读