折半查找

折半查找:

N个有序整数数列已放在一维数组中,利用二分查找法查找整数m在数组中的位置。若找到,则输出其下标值;反之,则输出“Not be found!”。

 

代码:

#include<iostream>

#define N 10

using namespace std;

int main()

{

    int a[N],mid,high=N-1,low=0,k=-1,x;

    cout<<"a数组中的数据如下:"<<endl;

    for(int i=0;i<N;i++)

        cin>>a[i];//输入数据

    cout<<"Enter x:";

    cin>>x;

    while(low<=high)

    {

        mid=(low+high)/2;//确定mid的位置

        if(x<a[mid])

            high=mid-1;

        else if(x>a[mid])

            low=mid+1;

        else

        {

            k=mid;

            break;//找到所需的数跳出循环

        }

    }

    if(k>=0)

        cout<<"x="<<x<<",index="<<k<<endl;

    else

        cout<<"Not be found!"<<endl;

    return 0;

}

 

该题体会:学会了折半查找

posted @ 2023-04-15 13:53  不如喝点  阅读(35)  评论(0)    收藏  举报