c++ stl二分查找与lower_bound

  1. 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
}
  1. 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;
}
  1. 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实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值