int binarySearch(const vector<int> & v, int k)? Implement a function that uses b
ID: 3552064 • Letter: I
Question
int binarySearch(const vector<int> & v, int k)?Implement a function that uses binary search to search for a given value in a vector of integers whose elements are in strictly increasing order. If the value is found, the function returns the index of the value in the vector? otherwise, it returns 1. You can assume that the values passed into the function are in strictly increasing order. Forexample, for v = (2,4, 5, 6, 8) and k=1, the function returns 1, and for k =18 it returns 2 . A declaration of the function is shown above.
int binarySearch(const vector<int> & v, int k)?
Implement a function that uses binary search to search for a given value in a vector of integers whose elements are in strictly increasing order. If the value is found, the function returns the index of the value in the vector? otherwise, it returns 1. You can assume that the values passed into the function are in strictly increasing order. Forexample, for v = (2,4, 5, 6, 8) and k=1, the function returns 1, and for k =18 it returns 2 . A declaration of the function is shown above.
Implement a function that uses binary search to search for a given value in a vector of integers whose elements are in strictly increasing order. If the value is found, the function returns the index of the value in the vector? otherwise, it returns 1. You can assume that the values passed into the function are in strictly increasing order. Forexample, for v = (2,4, 5, 6, 8) and k=1, the function returns 1, and for k =18 it returns 2 . A declaration of the function is shown above.
Explanation / Answer
int binarySearch(const vector<int> & v, int k)
{
int low=0;
int high=v.size()-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(v[mid]==k)
return mid;
else if(v[mid]<k)
low=mid+1;
else
high=mid-1;
}
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.