Two-point retrieval technology

recursive algorithm
#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);
    }

intmain()
{
    cout<<"Please enter the number n of the ancestors in the sequence: ";
    while(cin>>n)
    {
        cout<<"Please enter the elements in the sequence: ";
        for(i=0;i<n;i++)
        {
            cin>>s[i];
        }
        sort(s,s+n);
        cout<<"The sorted array is ";
        for(i=0;i<n;i++) cout<<s[i]<<" ";
        cout<<endl;
        cout<<"Please enter the searched element";
        cin>>x;
        i=binaryseach(s,x,0,n-1);
        if(i==-1)
            cout<<"There is no element to find here, go away";
        else
            cout<<"元素在"<<i+1<<"位"<<endl;
    }
    return 0;
}

Ordinary algorithm

#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;
}

intmain()
{
    cout<<"Please enter the number n of the ancestors in the sequence: ";
    while(cin>>n)
    {
        cout<<"Please enter the elements in the sequence: ";
        for(i=0;i<n;i++)
        {
            cin>>s[i];
        }
        sort(s,s+n);
        cout<<"The sorted array is ";
        for(i=0;i<n;i++) cout<<s[i]<<" ";
        cout<<endl;
        cout<<"Please enter the searched element";
        cin>>x;
        i=binaryseach(n,s,x);
        if(i==-1)
            cout<<"There is no element to find here, go away";
        else
            cout<<"元素在"<<i+1<<"位"<<endl;
    }
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325979795&siteId=291194637