linux下练习 c++ 二分查找

#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

 

linux下练习 c++ 二分查找

 

上一篇:【MaxCompute季报】MaxCompute新功能发布 2019Q3


下一篇:北京创业公司诚聘ASP.NET(C#)程序员【全职】