Binary search if array contains duplicates

后端 未结 5 1196
慢半拍i
慢半拍i 2021-02-11 04:05

Hi,

what is the index of the search key if we search for 24 in the following array using binary search.

array = [10,20,21,24,24,24,24,24,30,40,45]
         


        
5条回答
  •  醉酒成梦
    2021-02-11 04:50

    public class a{
        public static int binarySearch(int[] array, int value, int left, int right) {
              if (left > right)
                    return -1;
              int middle = (left + right) / 2;
              if (array[middle] == value)
            {
                if(array[middle-1] value)
                    return binarySearch(array, value, left, middle - 1);
              else
                    return binarySearch(array, value, middle + 1, right);           
        }
    public static int binarySearch1(int[] array, int value, int left, int right) {
              if (left > right)
                    return -1;
              int middle = (left + right) / 2;
              if (array[middle] == value)
            {
                if(array[middle] value)
                    return binarySearch1(array, value, left, middle - 1);
              else
                    return binarySearch1(array, value, middle + 1, right);           
        }
    
        public static void main(String[] args) {
            int[] data = new int[] {10,20,21,24,24,24,24,24,30,40,45};
    
    
            System.out.println(binarySearch(data, 24, 0, data.length - 1));     //First Index
            System.out.println(binarySearch1(data, 24, 0, data.length - 1));    //Last Index
        }
    }
    

提交回复
热议问题