c# - 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 循环中的值,而且我的大于和小于符号混淆了。
解决方案
在最后的主算法循环中,您永远不会重新计算compareResult
,因此您的程序无法判断它何时找到了某些东西。
您需要compareResult = String.compare ...
在if
andelse if
块中添加一个。.
如果您不这样做,compareResult
将保留您在循环之前进行的第一次比较的结果。
推荐阅读
- vba - 运行时错误“1004”:数据透视表字段名称无效
- mysql - 阿拉伯语单词更改为???? 插入Mysql DB后
- sql - 为表 B 中的每一行选择表 A 中的每一行
- c# - 在 SQL Server 2016 中加密列时如何查询数据
- python - Python:使用“for _ in sys.stdin”从标准输入读取需要两个 Ctrl+D 退出?
- javascript - Axios 通用 Post 在 TypeScript 中返回错误类型
- java - 设置适配器上的空对象引用
- http - ActivePDF Rest API 与 Coldfusion 一起使用
- sql - 获取一个表的所有行,并匹配另一个表中可能不存在 SQL 条目的行
- javascript - 通过单选按钮将值插入 Firebase