第十三週項目1-驗證算法2

/*               
*Copyright (c) 2017,煙臺大學計算機與控制工程學院               
*All rights reserved.               
*文件名稱:項目1-驗證算法          
*作    者:董麗娟               
*完成日期:2017年11月23日               
*版 本 號:v1.0                  
*/         

分塊查找:

#include <stdio.h>
#define MAXL 100    //數據表的最大長度
#define MAXI 20     //索引表的最大長度
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
    KeyType key;                //KeyType爲關鍵字的數據類型
    InfoType data;              //其他數據
} NodeType;
typedef NodeType SeqList[MAXL]; //順序表類型

typedef struct
{
    KeyType key;            //KeyType爲關鍵字的類型
    int link;               //指向對應塊的起始下標
} IdxType;
typedef IdxType IDX[MAXI];  //索引表類型

int IdxSearch(IDX I,int m,SeqList R,int n,KeyType k)
{
    int low=0,high=m-1,mid,i;
    int b=n/m;              //b爲每塊的記錄個數
    while (low<=high)       //在索引表中進行二分查找,找到的位置存放在low中
    {
        mid=(low+high)/2;
        if (I[mid].key>=k)
            high=mid-1;
        else
            low=mid+1;
    }
    //應在索引表的high+1塊中,再在線性表中進行順序查找
    i=I[high+1].link;
    while (i<=I[high+1].link+b-1 && R[i].key!=k) i++;
    if (i<=I[high+1].link+b-1)
        return i+1;
    else
        return 0;
}

int main()
{
    int i,n=25,m=5,j;
    SeqList R;
    IDX I= {{14,0},{34,5},{66,10},{85,15},{100,20}};
    KeyType a[]= {8,14,6,9,10,22,34,18,19,31,40,38,54,66,46,71,78,68,80,85,100,94,88,96,87};
    KeyType x=85;
    for (i=0; i<n; i++)
        R[i].key=a[i];
    j=IdxSearch(I,m,R,n,x);
    if (j!=0)
        printf("%d是第%d個數據\n",x,j);
    else
        printf("未找到%d\n",x);
    return 0;
}

運行結果:


知識點總結:

分塊查找

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章