1. 程式人生 > >折半查詢法實現

折半查詢法實現

折半查詢法的思想是:減少查詢序列的長度,分而治之的進行關鍵字的查詢。

方法一:迭代實現

#include <stdio.h>

int bin_search(int str[],int size,int key)
{
    int low,mid,high;
    low=0;
    high=size-1;

    while(low<=high)
    {
        mid=(low+high)/2;

        if(str[mid]==key)
            return mid;
        else if(str[mid]<key)
            low=mid+1;
        else if(str[mid]>key)
            high=mid-1;
    }

    return -1;
}

int main()
{
    int str[11]={1,1,2,3,5,8,13,21,34,55,89};
    int n,addr;
    
    printf("請輸入要查詢的關鍵字:");
    scanf("%d",&n);

    addr=bin_search(str,11,n);

    if(-1!=addr)
        printf("查詢成功,要查詢的關鍵%d在%d處\n",n,addr);
    else
        printf("查詢失敗");

    return 0;

}

方法二:遞迴實現:

#include <stdio.h>

int search(int str[],int n,int key)
{
    int m,low=0,high=n-1;
    int mid=(high+low)/2;

    if(str[mid]==key)
        return mid;

    if(str[low]>=str[high])
        return -1;

    if(str[mid]>key)
    {
        high=mid-1;
        m=search(&str[low],high-low+1,key);
    }
    else if(str[mid]<key)
    {
        low=mid+1;
        m=search(&str[low],high-low+1,key);
    }

    if(m!=-1)
        m=m+low;

    return m;
}

int main()
{
    int str[11]={1,1,2,3,5,8,13,21,34,55,89};
    int n,addr;

    printf("請輸入要查詢的關鍵字:");
    scanf("%d",&n);

    addr=search(str,11,n);

    if(addr!=-1)
        printf("查詢成功,要查詢的關鍵%d處於位置%d\n",n,addr);
    else 
        printf("查詢失敗\n");

    return 0;
}