二分法查找

#include <iostream>
using namespace std;
#define  TOTAL_COUNT 1001
bool bin_search(int a[],int n,int key)
{
    int low,hight,mid;
    low = 0;
    hight = TOTAL_COUNT -1;  //最高位减一
    mid = (low+hight)/2; 
    while(low<hight)
    {
        if ( a[mid] == key )
        {
            cout << "Find Key  " << key << endl;
            return true;
        }
        if ( a[mid] > key )
        {
            hight = a[mid];
        }
        if ( a[mid] < key )
        {
            low = a[mid+1];
        }
        mid = (low+hight)<<1; //防止溢出采用移位操作
    }
    cout << "Not Find Key  " << key << endl;
    return false ;
}
int main()
{
    int a[TOTAL_COUNT];
    for ( int i=0;i< TOTAL_COUNT;i++)
    {
        a[i] = i;
    }
    bin_search(a,TOTAL_COUNT,999);
    getchar();
}


你可能感兴趣的:(面试相关)