Below is my Generic Binary Search. It works okay with the integers type array (it finds all the elements in it). But the problem arises when I use a string array to find any
pst Your advice really worked. :) this code is working for both int and string.
public static int BinarySearch(T[] array, T searchFor, Comparer comparer)
{
int high, low, mid;
high = array.Length - 1;
low = 0;
if (array[0].Equals(searchFor))
return 0;
else if (array[high].Equals(searchFor))
return high;
else
{
while (low <= high)
{
mid = (high + low) / 2;
if (comparer.Compare(array[mid], searchFor) == 0)
return mid;
else if (comparer.Compare(array[mid], searchFor) > 0)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
}