天天看点

数据结构与算法------线性查找

线性查找

1.算法:逐个比较,找到为止。

2.评价:O(N),对数据的有序性没有要求。

#include<iostream>
#include<cstdlib>
using namespace std;
int lfind(int *data,int size,int value){//线性查找->返回元素下标
    for(int i=;i<size;++i)
        if(data[i]==value)
            return i;
    return -;
}
int main(){
    int *data=new int;
    int size,value;
    cout<<"Pls input the size:";
    cin>>size;
    srand(time());
    for(int i=;i<size;++i){
        data[i]=rand()%;
    }
    cout<<"Pls input the value:";
    cin>>value; 
    int ret=lfind(data,size,value);
    if(ret==-)
        cout << "Not found" << endl;
    else
        cout<<"data["<<ret<<"] = "<<value<<endl;

    return ;
}
           

测试结果:

Pls input the size:1234

Pls input the value:123

data[126] = 123

继续阅读