Below is my Generic Binary Search it works ok with the intgers type array it finds all the elements in it . But the Problem Arises when i use a string array to find any string data. It runs ok for the first index and last index elements but i cant find the middle elements.
Stringarray = new string[] { "b", "a", "ab", "abc", "c" };
public static void BinarySearch<T>(T[] array, T searchFor, Comparer<T> comparer) {
int high, low, mid;
high = array.Length - 1;
low = 0;
if (array[0].Equals(searchFor))
Console.WriteLine("Value {0} Found At Index {1}",array[0],0);
else if (array[high].Equals(searchFor))
Console.WriteLine("Value {0} Found At Index {1}", array[high], high);
else
{
while (low <= high)
{
mid = (high + low) / 2;
if (comparer.Compare(array[mid], searchFor) == 0)
{
Console.WriteLine("Value {0} Found At Index {1}", array[mid], mid);
break;
}
else
{
if (comparer.Compare(searchFor, array[mid]) > 0)
high = mid + 1;
else
low = mid + 1;
}
}
if (low > high)
{
Console.WriteLine("Value Not Found In the Collection");
}
}
}