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;
}
};
bin_searchrecursively, what are you doing with the the result those calls returns?m=bin_search(nums,target,l,m)should be there in the code.bin_search()insidebin_search()and throwing the resulting value away makes no sense.