zoukankan      html  css  js  c++  java
  • 二分查找的两种方式

    /*
     * 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;
    	}
    }
    



  • 相关阅读:
    两个服务器上SQLServer实例之间配置Service Broker示例
    处理数据库镜像问题的一个案例
    oracel修改密码
    Oracle报错
    如何创建ORACLE大文件表空间
    创建、删除表空间
    oracle中新建用户和赋予权限
    非常全的VsCode快捷键
    VS Code常用快捷键
    启动Weblogic问题集锦
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3237141.html
Copyright © 2011-2022 走看看