Without commenting on the details of your algorithm, there are some issues with your code. You could've found all these issues by looking at the compiler's error messages.
You return
true
andfalse
, yet your method specifies it returnsvoid
. Change that tobool
instead.public bool SearchLibrary(string bookName)
You do
!bookName
, where I presume you want to check whether it isnull
or not. You must do that explicitly in C#.while (bookName != null)
You compare two strings, but the
<
operator is not overloaded for strings. UseCompareTo
instead:else if (bookName.CompareTo(library[mid]) < 0)
Not all code paths return a value. You'll have to return a value no matter what execution path it takes. For example, end your method with this:
return false;
Then there is an issue with your algorithm: it will run forever when there is no match. As I suspect this may be homework, I'll leave it an an exercise for the OP to solve this issue.
And if this isn't a homework exercise, you could've saved yourself some trouble:
The List<T>
class has a method BinarySearch
that uses the default comparer to compare the objects in the list.
library.Sort();
bool found = (library.BinarySearch(bookName) >= 0);