二分收索技术

递归算法
#include<bits/stdc++.h>
using namespace std;
const int M=10000;
int x,n,i;
int s[M];
int binaryseach(int s[],int x,int low,int high)
{
    if(low>high) return -1;
    int middle=(low+high)/2;
    if(x==s[middle])
            return middle;
        else if(x<s[middle])
            return binaryseach(s,x,low,middle-1);
        else return binaryseach(s,x,middle+1,high);
    }

int main()
{
    cout<<"请输入数列中元祖的个数n为:";
    while(cin>>n)
    {
        cout<<"请依次输入数列中的元素:";
        for(i=0;i<n;i++)
        {
            cin>>s[i];
        }
        sort(s,s+n);
        cout<<"排序后的数组为";
        for(i=0;i<n;i++) cout<<s[i]<<" ";
        cout<<endl;
        cout<<"请输入查找后的元素";
        cin>>x;
        i=binaryseach(s,x,0,n-1);
        if(i==-1)
            cout<<"这里没有要查找的元素,快滚吧";
        else
            cout<<"元素在"<<i+1<<"位"<<endl;
    }
    return 0;
}

普通算法

#include<bits/stdc++.h>
using namespace std;
const int M=10000;
int x,n,i;
int s[M];
int binaryseach(int n,int s[],int x)
{
    int low=0,high=n-1;
    while(low<high){
    int middle=(low+high)/2;
    if(x==s[middle])
            return middle;
        else if(x<s[middle])
            high=middle-1;
        else low=middle+1;
    }
    return -1;
}

int main()
{
    cout<<"请输入数列中元祖的个数n为:";
    while(cin>>n)
    {
        cout<<"请依次输入数列中的元素:";
        for(i=0;i<n;i++)
        {
            cin>>s[i];
        }
        sort(s,s+n);
        cout<<"排序后的数组为";
        for(i=0;i<n;i++) cout<<s[i]<<" ";
        cout<<endl;
        cout<<"请输入查找后的元素";
        cin>>x;
        i=binaryseach(n,s,x);
        if(i==-1)
            cout<<"这里没有要查找的元素,快滚吧";
        else
            cout<<"元素在"<<i+1<<"位"<<endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_40728285/article/details/79949204