数据结构(C++)——五种查找技术总结

#include 
#include 
using namespace std;
class Search
{
private:
    int * data;
    int length;
public:
    Search(int a[],int n);
    int SeqSearch(int k);
    int BinSearch_1(int k);
    int BinSearch_2(int x,int low,int height);
};
Search::Search(int a[],int n)
{
    data=new int[n+1];
    for(int i=0;i<n;i++)
    {
        data[i+1]=a[i];
    }
    length=n;
}
int Search::SeqSearch(int k)         //顺序查找 设置哨兵 查找平均长度O(n)
{
    data[0]=k;
    int i=length;
    while (data[i]!=k) {
        i--;
    }
    return i;
}
int Search::BinSearch_1(int k)       //二分查找 递归    查找平均长度O(log2n)
{
    int low=1,height=length;
    while (low<=height) {
        int mid=(low+height)/2;
        if(data[mid]<k)
            low=mid+1;
        else if(data[mid]>k)
            height=mid-1;
        else
            return mid;
    }
    return 0;
}
int Search::BinSearch_2(int x,int low,int height)  //二分查找 非递归    查找平均长度O(log2n)
{
    int mid;
    if(low>height)
        return 0;
    else
    {
        mid=(low+height)/2;
        if(data[mid]<x)
            return BinSearch_2(x, mid+1, height);
        else if(data[mid]>x)
            return BinSearch_2(x, low, mid-1);
        else
            return mid;
    }
}
int main()
{
    int a[5]={1,2,3,6,8};
    Search s(a,5);
    cout<<s.SeqSearch(1)<<endl;
    cout<<s.BinSearch_1(3)<<endl;
    cout<<s.BinSearch_2(6, 1, 5)<<endl;
}

你可能感兴趣的:(数据结构#查找,数据结构,算法,二分查找)