0

I'm stuck in the question. My code keeps returning 3 as output for the inputnums = [4,5,6,7,0,1,2], target = 0. I'm doing some modified version of binary search and printing the indices of middle index and checking whether value at that index is equal to the target value.Values of middle indices in binary search are stdout:3 5 4 but instead of returning 4 my program returns 3. Can you please tell me where my logic is incorrect?

class Solution {
public:
    int bin_search(vector<int>& nums,int target,int l,int r){
        int m;
        m=(r+l)/2;
        cout<<m<<" ";
        // if(r==l) break;
        if(nums[m]==target) return m;
        else if(r==l && nums[m]!=target) return -1;
        if(target>=nums[l] && target<=nums[m]){
            m=bin_search(nums,target,l,m);
        }
        else if(target>=nums[m+1] && target<=nums[r]){
            m=bin_search(nums,target,m+1,r);
        }
           
        
        // if(nums[m]==target) return m;
        return m;
    }
    
    int search(vector<int>& nums, int target) {
        int n=nums.size();
        int f;
        f=bin_search(nums,target,0,n-1);
        return f;
    }
};
4
  • 1
    Binary search can only be used with sorted arrays. (when applying to arrays) Commented Jun 18, 2021 at 11:48
  • 2
    When you call bin_search recursively, what are you doing with the the result those calls returns? Commented Jun 18, 2021 at 11:52
  • @Someprogrammerdude oh thanks m=bin_search(nums,target,l,m) should be there in the code. Commented Jun 18, 2021 at 11:59
  • Note that calling bin_search() inside bin_search() and throwing the resulting value away makes no sense. Commented Jun 18, 2021 at 13:09

1 Answer 1

1

You'll have to think on some modification in the binary search approach because binary search approach is applicable only for sorted array.

Hint : Think about finding some subarrays (which are sorted) and then apply binary search only on those specific parts.

Currently, you are not comparing a[low] & a[mid]. Only if you compare these two array indices, you'll get an idea of how the array elements are in the subarray (increasing or decreasing).

You are comparing a[low] & a[mid] with your target element , which will not output the desired relation of subarray(increasing or decreasing)

Sign up to request clarification or add additional context in comments.

3 Comments

I think I'm doing that can you confirm?
@anfjnlnl if you have any more concerns do let me know!
Strictly speaking, not only for sorted arrays. Take a look at std::binary_search() algorithm requirements.

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.