問題及代碼:
/*
*煙臺大學計算機與控制工程學院
*作 者:孫麗瑋
*完成日期:2016年11月27日
*問題描述:認真閱讀並驗證分塊查找算法。請用22,4,23,11,20,2,15,13,30,45,26,34,29,35,26,36,55,98,56,74,61,90,80,96,127,158,116,114,128,113,115,102,184,211,243,188,187,218,195,210,279,307,492,452,408,361,421,399,856,523,704,703,697,535,534,739(共n=56個數據,每塊數據個數s=8)作爲數據表,自行構造索引表,分別對查找61、739、200進行測試。
*/
#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=56,m=8,j;
SeqList R;
IDX I= {{23,0},{45,8},{98,16},{158,24},{243,32},{492,40},{856,48}};
KeyType a[]= {22,4,23,11,20,2,15,13,30,45,26,34,29,35,26,36,55,98,56,74,61,90,80,96,127,158,116,114,128,113,115,102,184,211,243,188,187,218,195,210,279,307,492,452,408,361,421,399,856,523,704,703,697,535,534,739};
KeyType x=200;
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;
}
運行結果:
總結:
分塊查找是先建立一個索引表,將數據表平分成幾塊,將每塊最大數劇作爲關鍵字,與要測試的數據進行比較,在相應塊中進行查找