mu_tou_man

导航

 
#include <iostream>
using namespace std;
//二分查找算法实现
int BinarySearch(int a[],int len,int findnum)
{
    int low = 0;    
    int high = len - 1;    
    while(low <= high)    
    {        
        int middle = (low + high)/2;        
        if(a[middle] == findnum)            
        {
            return middle;
        }
        else if(a[middle] > findnum)            
        {
            high = middle - 1;
        }
        else 
        {
            low = middle + 1;
        }
    }       
    return -1;
}
void main()
{
    int a[]={1,3,6,8,9,11,55,77,88};
    int leng=sizeof(a)/sizeof(int);
    int low=0;
    int hig=leng-1;
    int mid=(hig+low)/2;
    cout<<"please input the number you want to find: ";
    int findnum=0;
    cin>>findnum;
    int iRet=BinarySearch(a,leng,findnum);
    if (iRet==-1)
    {
        cout<<"没找到";
    }
    else
        cout<<iRet;
}

 

posted on 2014-08-11 15:21  mu_tou_man  阅读(285)  评论(0编辑  收藏  举报