Given an array of integers which is sorted in ascending order, and an integer target, write a function to search target in the array. If the target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
I solved the above question using the following code:
int search(int* nums, int numsSize, int target){
int l = 0;
int r = numsSize -1;
int result = -1;
while(l <= r)
{
int mid = (l + (r-l))/2;
if(nums[mid] == target)
return result = nums[mid];
if(nums[mid] < target)
return l = mid + 1;
else
return r = mid - 1;
}
return result;
}
But I am still not getting the right answer. Please help.
l == r) you automatically return-1even if that element matches the target.midas pointed out in Corina's answer below.