Binary search to find the range in which the number lies

后端 未结 10 749
悲哀的现实
悲哀的现实 2020-12-16 18:31

I have an array

Values array: 12 20 32 40 52
              ^  ^  ^  ^  ^
              0  1  2  3  4

on which I have to perform binary sear

10条回答
  •  心在旅途
    2020-12-16 19:14

    A regular binary search on success returns the index of the key. On failure to find the key it always stops at the index of the lowest key greater than the key we are searching. I guess following modified binary search algorithm will work.

    Given sorted array A
    Find a key using binary search and get an index. 
    If A[index] == key
        return index;
    else 
       while(index > 1 && A[index] == A[index -1]) index = index -1;
       return index;
    

提交回复
热议问题