CODE:
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;
}
}
}
}
PROBLEM: I am trying to code a C# binary search that searches a file with a list names (strings). For some reason I can't figure out, the search returns no results. Anyone have any ideas?
SOLUTION: I've fixed the code now. The two problems were that I wasn't comparing the value in the if and else if loops and I had my greater than and less than symbols mixed up.
compareResultin your lastwhileloop. You will be stuck with the compareResult of the first comparison you did before entering the loop.