Efficient way to count occurrences of a key in a sorted array

后端 未结 10 1533
粉色の甜心
粉色の甜心 2021-01-30 23:49

This was asked in on-site Microsoft interview.

Count the number of occurrences of a given key in an array.

I answered linear search because the elements may be s

10条回答
  •  失恋的感觉
    2021-01-31 00:16

    #include
    int binarysearch(int a[],int n,int k,bool searchfirst){
        int result=-1;
        int low=0,high=n-1;
        while(low<=high){
            int mid=(low+high)/2;
            if(a[mid]==k)  {
                  result=mid; 
               if(searchfirst)
                  high=mid-1; 
                else
                  low=mid+1;
        }
        else if(k

提交回复
热议问题