Binary search if array contains duplicates

后端 未结 5 1262
慢半拍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:49

    As pointed out by @Pleepleus it will return the index 5 from the first level of recursion itself. However I would like to point out few things about binary search :

    1. Instead of using mid = (left + right)/2 , use mid = left + (right-left)/2
    2. If you want to search for lower_bound or upper_bound of an element use the following algorithms:

      binLowerBound(a, lo, hi, x)
        if (lo > hi)
          return lo;
      
        mid = lo +  (hi - lo) / 2;
        if (a[mid] == x)
          return binLowerBound(a, lo, mid-1, x);
        else if (a[mid] > x)
          return binLowerBound(a, lo, mid-1, x);
        else
          return binLowerBound(a, mid+1, hi, x);
      
      binHigherBound(a, lo, hi, x)
        if (lo > hi)
          return lo;
        mid = lo + (hi - lo) / 2;
        if (a[mid] == x)
          return binHigherBound(a, mid+1, hi, x);
        else if (a[mid] > x)
          return binHigherBound(a, lo, mid-1, x);
        else
          return binHigherBound(a, mid+1, hi, x);
      

提交回复
热议问题