linux下练习 c++ 二分查找

简介: #include using namespace std; class person { string name; int age; public: person(const char* n,int a):name(n),age(a){} friend bool operator b.
#include<iostream>
using namespace std;
class person
{
	string name;
	int age;
public:
	person(const char* n,int a):name(n),age(a){}
	friend bool operator <(const person& a,const person& b)//运算符重载-比较年龄大小
	{
		return a.age<b.age;
	}
	friend bool operator >(const person& a,const person& b)//运算符重载-比较年龄大小
	{
		return a.age>b.age;
	}
	friend bool operator ==(const person& a,const person& b)//运算符重载-等于号
	{
		return a.age==b.age;
	}
	friend ostream& operator<<(ostream& o,const person& a)//运算符重载-输出
	{
		o<<a.name<<":"<<a.age<<endl;
	}
};
person* bsearch(person* a,int n,const int age)//二分查找
{
	if(n<=0) return NULL;
	int mid=n/2;
	person p("",age);
	if(a[mid]==p) return a+mid;
	if(p<a[mid]) return bsearch(a,mid,age);
	else return bsearch(a+mid+1,n-mid-1,age);
	
}
person* bsearch2(person* a,int n,const int age)//二分查找
{
	int b=0,e=n-1;
	person t("",age);
	while(b<=e)
	{
		int mid=(b+e)/2;
		if(a[mid]==t) return a+mid;
		if(t<a[mid]) e=mid-1;
		else b=mid+1;
	}
	return NULL;
	
}
int main()
{
	person a[5]={person("a1",34),
				person("a2",25),
				person("a3",16),
				person("a4",77),
				person("a5",40)};
	for(int i=0;i<5;i++)//排序
	{
		for(int j=i+1;j<5;j++)
			if(a[j]<a[i]) swap(a[j],a[i]);
	}
	for(int i=0;i<5;i++)
		cout<<a[i];
	int fage;
	cout<<"请输入要查找的年龄:";
	cin>>fage;
	person* p=bsearch2(a,5,fage);//查找
	if(p!=NULL) cout<<*p;
	else cout<<"未找到!\n";
}


g++ -o bsearch.out bsearch.cpp

bsearch.out

 

 

相关文章
|
1月前
|
存储 算法 Linux
【实战项目】网络编程:在Linux环境下基于opencv和socket的人脸识别系统--C++实现
【实战项目】网络编程:在Linux环境下基于opencv和socket的人脸识别系统--C++实现
64 7
|
4天前
|
JSON Java Linux
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
20 2
|
4天前
|
存储 安全 算法
【Linux | C++ 】基于环形队列的多生产者多消费者模型(Linux系统下C++ 代码模拟实现)
【Linux | C++ 】基于环形队列的多生产者多消费者模型(Linux系统下C++ 代码模拟实现)
21 0
|
4天前
|
算法 Linux 数据安全/隐私保护
【Linux | C++ 】生产者消费者模型(Linux系统下C++ 代码模拟实现)
【Linux | C++ 】生产者消费者模型(Linux系统下C++ 代码模拟实现)
12 0
|
13天前
|
存储 Linux C++
【进厂修炼 - First week】Linux & C++
【进厂修炼 - First week】Linux & C++
|
19天前
|
Linux C++
【代码片段】Linux C++打印当前函数调用堆栈
【代码片段】Linux C++打印当前函数调用堆栈
14 0
|
1月前
|
算法 测试技术 Serverless
【二分查找】【C++算法】378. 有序矩阵中第 K 小的元素
【二分查找】【C++算法】378. 有序矩阵中第 K 小的元素
|
1月前
|
人工智能 机器人 Linux
【C++】Linux下如何查看opencv的版本
【C++】Linux下如何查看opencv的版本
|
2月前
|
算法 Linux 编译器
⭐⭐⭐⭐⭐Linux C++性能优化秘籍:从编译器到代码,探究高性能C++程序的实现之道
⭐⭐⭐⭐⭐Linux C++性能优化秘籍:从编译器到代码,探究高性能C++程序的实现之道
170 2
|
2月前
|
数据采集 缓存 Linux
Linux C++ 应用开发:在Linux单线程应用中精确把握空闲时机
Linux C++ 应用开发:在Linux单线程应用中精确把握空闲时机
68 1