- binary_search实现
int myBinary_search(int arr[], int n, int target)
{
int first = 0, last = n;
int mid;
while (first < last)
{
mid = first + (last - first) / 2;
if (arr[mid] == target)
{
return mid;
}
else if ( target > arr[mid] )
{
first = ++mid;
}
else
{
last = mid;
}
}
return -1;
}
void test()
{
int arr[] = { 5,7,7,8,8,10 };
cout << myBinary_search(arr, 6, 1) << endl; //-1
cout << myBinary_search(arr, 6, 5) << endl; //0
cout << myBinary_search(arr, 6, 8) << endl; //3
cout << myBinary_search(arr, 6, 10) << endl;//5
}
- lower_bound实现
//返回指向范围 [first, last) 中首个不小于(即大于或等于) value 的元素的迭代器,或若找不到这种元素则返回 last 。
template<typename ForwardIter, typename T>
ForwardIter myLower_bound(ForwardIter first, ForwardIter last, T value)
{
while (first != last)
{
auto mid = next(first, distance(first, last) / 2);
if (value > *mid) first = ++mid;
else last = mid;
}
return first;
}
//返回指向范围 [first, last) 中首个大于 value 的元素的迭代器,或若找不到这种元素则返回 last 。
template<typename ForwardIter, typename T>
ForwardIter myUpper_bound(ForwardIter first, ForwardIter last, T value)
{
while (first != last)
{
auto mid = next(first, distance(first, last) / 2);
if (value >= *mid) first = ++mid;
else last = mid;
}
return first;
}
- cppreference.com
//可能的实现
//版本一
template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value)
{
first = std::lower_bound(first, last, value);
return (!(first == last) && !(value < *first));
}
//版本二
template<class ForwardIt, class T, class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
first = std::lower_bound(first, last, value, comp);
return (!(first == last) && !(comp(value, *first)));
}
myBinary_search根据lower_bound实现