二分法:(分治+递归) binary search:
用于在一组已排序数据中查找需要的值的位置
在一组已排序数据
如果数值个数为0 返回空否则在右串中查找的结果
#include <iostream> using namespace std; class Person { string name; int age; string addr; public: Person(const char *name,int age,const char *addr):name(name),age(age),addr(addr){} 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<< a.name << ',' << a.age << ',' << a.addr; return o; } }; //两种方法: //二分查找 递归法 Person* binary_search(Person*a,int size,string name) { if(size <=0 ) return NULL; Person t(name.c_str() ,0 ,""); int mid = size/2; if(a[mid] == t) return a+mid; //1个 else if(t < a[mid]) return binary_search(a,mid,name); //mid个 else return binary_search(a+mid+1,size-mid -1,name); //size-1-mid个 } //二分查找 非递归 Person* binary_search2(Person*a,int size,string name) { int b=0,e=size-1; Person t(name.c_str() ,0 ,""); while(b<=e) { int mid = (b+e)/2; if(a[mid] == t) return a+mid; else if(t < a[mid]) e=mid-1; else b = mid+1; } return NULL; } int main() { Person a[5]={Person("何君君",20,"重庆"), Person("李零",21,"新疆"), Person("钟玉龙",23,"大连"), Person("蒲虚两",16,"四川"), Person("王刚",18,"吉林") }; for(int i=0;i<5;i++) { for(int j=i+1;j<5;j++) { if(a[j] < a[i]) { /* Person temp = a[j]; a[j] = a[i]; a[i] = temp; */ swap(a[i],a[j]); } } } for(int i =0; i< 5; i++) //VC 中这么写是通不过的,编译器认为重复定义了i { cout << a[i] << endl; } cout << "请输入查找的名字" <<endl; string name; cin >> name; Person *p = binary_search(a,5,name); if(p == NULL) { cout << "该人物不存在" << endl; } else { cout << *p << endl; } }