Home > Net >  I am stuck in this binary search problem in geeks for geeks (time limit exceeded)
I am stuck in this binary search problem in geeks for geeks (time limit exceeded)

Time:07-11

C I don't know what went wrong or am I missing something ? always getting a time limit exceeded.

class Solution {
  public:
    int binarysearch(int arr[],int n,int k){

        int low  = 0;
        int high = n-1;
        while(low < high){
            int mid = (low   high)/2;
            if(arr[mid] == k){
                return mid;
            }
            else if(arr[mid] < k){
                high = mid   1;
            }
            else{
                low = mid-1;
            }
        }
        return -1;
    }
};

CodePudding user response:

Here's a hint.

Take a closer look at this:

        else if(arr[mid] < k){
            high = mid   1;
        }
        else{
            low = mid-1;
        }

Now ask yourself. If arr[mid] is less than the value to be searched for, what range of indices should be searched for on the next iteration? Then compare that to what the code is actually doing.

  •  Tags:  
  • c
  • Related