Binary search
Code implementation
1. Recursion
#include <iostream>
#include <vector>
class BSException: public std::runtime_error{
public:
explicit BSException(const char* message): std::runtime_error(message){}
};
int binarySearch(const std::vector<int>& array, int target, int lower, int upper)
{
int center, range;
range = upper - lower;
if (range <0){throw BSException("Limits reversed");}
else if(range==0 && array[lower]!=target){throw BSException("Element not in array.");}
if (array[lower] > array[upper]) {throw BSException("Array not sorted");}
center = (range/2) + lower;
if (target==array[center]){return center;}
else if (target<array[center]){binarySearch(array, target, lower, center-1);}
else{binarySearch(array, target, center+1, upper);}
}
int bsearch(const std::vector<int>& array, int target)
{
return binarySearch(array, target, 0, array.size()-1);
}
2. Iterative method
int binarySearch(const std::vector<int>& array, int target, int lower, int upper)
{
int range, center;
while (true){
range = upper - lower;
if (range < 0){throw BSException("limits reversed!");}
else if (range==0 && array[lower]!=target){throw BSException("Element not in array.");}
if (array[lower]>array[upper]){throw BSException("array is not sorted");}
center = range/2 + lower;
if (array[center]==target){return center;}
else if (target>array[center]){lower=center+1;}
else {upper=center-1;}
}
}
Test
int main(){
std::vector<int> sortedArray = {1,4,6,10, 13,15,16, 19};
int target= 6;
try{
int result=bsearch(sortedArray, target);
std::cout << "Element found at index: " << result << std::endl;
}catch(const BSException& e){
std::cout << "Error: " << e.what() << std::endl;
}
target = 4;
try{
int result=bsearch(sortedArray, target);
std::cout << "Element found at index: " << result << std::endl;
}catch(const BSException& e){
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
Time complexity
- if the array is already sorted, O(logn)