int binarySearch(vector<int> &v, int target, int start, int end){
// pass start and end into the list so that we do not need to make copies of the vector
if (start >= end || start < 0 || end > v.size()-1){
// edge cases
return -1;
}
int mid = start + (end - start) / 2;
if (v[mid] == target){
return mid;
}
else if (v[mid]) > target){
// search left half
binarySearch(v, target, start, mid-1);
}
else if (v[mid] < target){
// search right half
binarySearch(v, target, mid+1, end);
}
return -1;
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.