Generic Binary Search in C#

前端 未结 4 923
醉酒成梦
醉酒成梦 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:24

    //Binary search recursive method

        public void BinarySearch(int[] input,int key,int start,int end)
        {
            int index=-1;
            int mid=(start+end)/2;
            if (input[start] <= key && key <= input[end])
            {
                if (key < input[mid])
                    BinarySearch(input, key, start, mid);
                else if (key > input[mid])
                    BinarySearch(input, key, mid + 1, end);
                else if (key == input[mid])
                    index = mid;
                if (index != -1)
                    Console.WriteLine("got it at " + index);
            }
        }  
    
         int[] input4 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };   
         BinarySearch(input4, 1, 0, 8);
    

提交回复
热议问题