二分查找的两种方式
/* * query.cpp * * Created on: 2013年8月4日 * Author: Administrator */ #include <iostream> using namespace std; class Person{ string name; int age; string salary; public: Person(string name , int age , string salary):name(name),age(age),salary(salary){ } friend bool operator<(const Person& a , const Person& b ){ return a.name < b.name; } friend bool operator==(const Person& a ,const Person& b){ return a.name == b.name; } friend ostream& operator<<(ostream& o , const Person& a){ o<<"name"<<" : "<<a.name << " salary: "<<a.salary; return o; } //以下是递归调用的方式 friend Person* binarysearch(Person* p , int n , string name){ if( n == 0 ){ return NULL; } int mid = n/2; Person a(name,0,""); if(p[mid] == a){ return p + mid; }else if( a < p[mid] ){ return binarysearch(p,mid,name); }else{ return binarysearch(p+mid+1,n - mid - 1,name); } } friend Person* binarysearch1(Person* p , int n , string name){ cout<<"这时使用非递归版的二分查找"<<endl; int l = 0; int r = n - 1; Person t(name,0,""); while( l <= r){ int mid = (l+r)/2; if(p[mid] == t){ return p + mid; }else if( t < p[mid] ){ r = mid - 1; }else{ l = mid + 1; } } return NULL; } }; int main(){ Person persons[3]={ Person("allen",21,"40000"), Person("bllen",22,"41000"), Person("cllen",23,"42000") }; cout<<"请输入您要查找的人的名字:"; string name ; cin >> name; Person* p = binarysearch1(persons,3,name); if(p == NULL){ cout<< "没有找到"<<endl; }else{ cout<< *p <<endl; } }