Generic Binary Search in C#

前端 未结 4 898
醉酒成梦
醉酒成梦 2020-12-16 22:25

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

4条回答
  •  时光说笑
    2020-12-16 23:20

    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;                
            }                 
        }
    

提交回复
热议问题