查找

#include<iostream>
using namespace std;
int Search_Seq(int arr[],int arr_size,int key)//表数据从1开始到下标处,arr_size表示数组大小
{
    int i;
    arr[0]=key;
    for( i=arr_size-1;i>0;i--)
    {
        if(arr[i]==key)
        {
            return i;
        }
    }
    return i;
}
static int F[100];

void initF()
{
    F[0]=0;
    F[1]=1;
    for(int i=2;i<100;i++)
    {
        F[i]=F[i-1]+F[i-2];
    }
}

int Search_Fibonacci(int arr[],int arr_size,int key)
{
    int low=0;
    int index=0;
    while(arr_size>F[index]-1)
    {
        index++;
    }
    for(int i=arr_size-1;i<F[index]-1;i++)
    {
        arr[i]=arr[arr_size-1];
    }
    int high=F[index]-1-1;
    while(low<=high)
    {
        int mid=low+F[index-1]-1;
        if(arr[mid]==key)
        {
            if(mid<=arr_size-1)
            {
                return mid;
            }
            else
            {
                return -1;
            }
        }
        else if(arr[mid]<key) 
        {
            low =mid+1;
            index-=2;

        }else if(arr[mid]>key)
        {
            high=mid-1;
            index--;
        }
    }
    return -1;




}




int Search_Seq2(int arr[],int arr_size,int key)
{
    arr[0]=key;
    int i=arr_size-1;
    while(arr[i]!=key)
    {
        i--;
    }
    return i;
}
int Search_Binary(int arr[],int arr_size,int key)
{
    int low=0;
    int high=arr_size-1;
    int mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(arr[mid]==key)return mid;
        if(arr[mid]<key) 
        {
            low=mid+1;        
        }
        if(arr[mid]>key)
        {
            high=mid-1;
        }
    }
    return -1;
}


int main()
{
    initF();


    int arr[7]={11,44,67,78,89,132,434};
    cout<<Search_Fibonacci(arr,7,442);
    //cout<<Search_Seq(arr,7,3);
    //cout<<Search_Binary(arr,7,4331);
    //cout<<Search_Seq2(arr,7,119);
    getchar();

}

 

posted on 2016-08-02 15:48  达达123567  阅读(190)  评论(0编辑  收藏  举报

导航