折半查找法查找一个数是数组中的第几个数如果没有则输出“查无此数”

#include <iostream>
using namespace std;
int main()
{
    int a[15]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,145};
    cout<<"请输入要查找的数";
    int n;
    cin>>n;
    int l=0;
    int m=14;//从最末尾和最开始查;
    int h;//中间的折半查找 
    while(l<m) {
        h=(l+m)/2;
        if(a[h]==n)
        break;//找到后停止查找;退出循环
        else if(a[h]>n) //上限发生变化
        m=h-1;
        else
        l=h+1 ;
        
    }
    cout<<"是第"<<h+1<<"个数" ;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_62802660/article/details/122539919