0

I am trying to implement a modified version of Binary Search which returns the position of the next greatest value from a given key , from a sorted array.

Here's the code -- (lli refers to long long int)

lli search(vector<lli>arr,lli key)
{
    lli low=0,high=arr.size() - 1,mid,pos=-1;

    while(low<=high)
    {
        mid=low + (high-low)/2;

         if(arr[mid]<key)
            low=mid+1;
        else{
                pos=mid;
                high=mid-1;
            }
    }
    return pos;
}

Here arr is the sorted array and we have to find the position of the next greatest element than the key in the array arr.

I have taken care that the key is between [min(arr),max(arr)].So, pos will have a value in [0 ,arr.size() - 1] .

The method runs for many values I can think of but the online judge rejects it with Time Limit Exceeded error. Is there an infinite loop possible here?

2
  • Why are you calculating the mid in that way? Is that how you intended to modify the binary search? Commented May 22, 2017 at 18:41
  • @AlexS high and low are values upto 10^9 so adding them for mid = (high+low)/2 can cause problems. Commented May 22, 2017 at 18:42

1 Answer 1

0

you can solve as a regular binary search but use

if (arr[mid] == key){
    if (mid == arr.size() - 1)
         return -1; // key was the last element, there is nothing after it
    return mid + 1;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.