搜索(c++)

本文介绍了两种二分查找的实现方式:一种是纯手动实现的二分查找算法;另一种则是使用C++标准库提供的lower_bound和upper_bound函数进行查找。通过具体的代码示例详细解释了这两种方法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分查找

# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
int main(){
	int m , n , x;
	cin >> n >> m ;
	int a[1000];
	for (int i = 0 ; i < n ; i++)
		cin >> a[i];
	while (m -- ){
		cin >> x; 
		int left = 0 ,right = n ;
		while (left < right ){
			int mid = (left + right ) / 2;
			if (a[mid] >= x)
				right = mid ;
			else left = mid + 1;
		}
		if (a[left]!=x){
			cout << " no "<< endl;		
			continue;
		}
		cout << left << endl;
		
	}
	return 0  ;
}

lower_bound 和 upper_bound 在algorithm 头文件中 利用 二分查找 对有序数组进行查找

lower_bound 会返回数组中大于等于 被查数 的 地址 , 查找坐标即  -a

upper_bound 返回数组 小于 被查数 的地址 ,查找坐标 -a 

# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
const int N = 2000000;
int main(){
	int m , n , x;
	cin >> n >> m ;
	int a[1000];
	int b[1000];
	for (int i = 0 ; i < n ; i++)
		cin >> a[i];
	int cnt = 0 ; 
	sort (a, a+n );
	while ( m -- ){
		cin >> x ;
		int t1 = upper_bound(a,a+n,x) - a ;//找出 数组中 第一个小于被查数x的坐标 
		int t2 = lower_bound(a,a+n,x) - a; // 找出数组中第一个大于或等于 被查数的坐标
	cout << a[t1] << endl ;
	cout << a[t2] << endl ;
}
	return 0  ;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值