基本的查找算法示例

顺序查找-比较简单,循环比较即可
/*Find*/
//顺序查找算法,循环比较即可
#include <iostream>
#include <time.h>
#define N 15
using namespace std;
int Search(int a[],int n,int key)
{
    int i,f=-1;
    for(i=0;i<n;i++)
    {
        if(key==a[i])
        {
            f=i;
            break;
        }
    }
    return f;
};

int main() {
    cout<<"hello"<<endl;
    int shuzi[N];
    srand(time(NULL));
    for(int i=0;i<N;i++)
    {
        shuzi[i]=rand()%100;
    }
    cout<<"************show the data*************"<<endl;
    for(int i=0;i<N;i++)
    {
        cout<<shuzi[i]<<" ";
    }
    cout<<endl;
    cout<<"input the number you want to find"<<endl;
    int temp;
    cin>>temp;
    int pos = Search(shuzi,N,temp);
    if(pos<0)
    {
        cout<<"can't find the data!"<<endl;
    }
    else
    {
        cout<<"the data is located in SHUZI at "<<pos+1<<endl;
    }
    return 0;
}

折半查找-适用于有序的数据的查询

/*折半查找*/
#include <iostream>
using namespace std;
#define N 15
int Search(int a[],int n,int key)
{
    int mid,low,high;
    low = 0;
    high = n-1;
    while(low<=high)
    {
        mid = (low+high)/2;
        if(a[mid]==key)
            return mid;
        else
        {
            if(a[mid]>key)
                high = mid-1;
            if(a[mid]<key)
                low = mid+1;
        }
    }
    return -1;
}
int main()
{
    int shuzi[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    /*srand(time(NULL));
    for(int i=0;i<N;i++)
    {
        shuzi[i]=rand()%100;
    }*/
    cout<<"************show the data*************"<<endl;
    for(int i=0;i<N;i++)
    {
        cout<<shuzi[i]<<" ";
    }
    cout<<endl;
    cout<<"input the number you want to find"<<endl;
    int temp;
    cin>>temp;
    int pos = Search(shuzi,N,temp);
    if(pos<0)
    {
        cout<<"can't find the data!"<<endl;
    }
    else
    {
        cout<<"the data is located in SHUZI at "<<pos+1<<endl;
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值