本实验将通过C语言实现基于线性探测法的散列表
散列表(Hash Table)是一种常见的数据结构,通过使用哈希函数将关键字映射到一个固定大小的数组中。这样可以通过计算关键字的哈希值,将其直接映射到数组的索引,实现快速的数据查找。
线性探测法是一种处理哈希冲突的方法,当发生冲突时,线性探测法会沿着数组顺序地查找下一个可用的位置,直到找到一个空槽。这样可以避免冲突,确保每个关键字都能插入到散列表中。
编写算法构造教材图 8.47 的拉链表,输出散列表每个槽对应的单链表,并编程计算查找成功时的平均查找长度。
char *A[30]={
"THE","OF","AND","TO","A",
"IN","THAT","IS","WAS","HE",
"FOR","IT","WITH","AS","HIS",
"ON","BE","AT","BY","I",
"THIS","HAD","NOT","ARE","BUT",
"FROM","OR","HAVE","AN","THEY",
};
散列表数组:
char *TABLE[31] = { "\0" };
数组 TABLE
,包含 31 个元素,每个元素是一个字符串指针。
插入函数 L
:
void L(char *TABLE[31], char *K, int M)
{
int i = B[N];
while (TABLE[i])
{
sum++;
if (strcmp(TABLE[i], K) == 0)
return;
i = (i + 1) % M;
}
if (N < M - 1)
{
TABLE[i] = K;
N++;
return;
}
return;
}
插入函数 L
用于在散列表中插入数据。当发生冲突时,使用线性探测法沿着数组查找下一个可用的位置。
主函数:
int main(){
char *A[30] = { /* ... */ };
char *TABLE[31] = { "\0" };
int i;
for (i = 0; i < 30; i++){
L(TABLE, A[i], 31);
}
for (i = 0; i < 31; i++){
if (TABLE[i])
printf("%d:%s\n", i, TABLE[i]);
else
printf("%d:NULL\n", i);
}
N = 0;
sum = 0;
for (i = 0; i < 30; i++){
L(TABLE, A[i], 31);
N++;
}
printf("\n平均查找长度为%f", (float)sum / 30);
}
#include
#include
int B[31]={
25,9,11,27,1,7,9,26,5,13,
27,29,2,18,18,1,7,21,27,9,
6,13,21,22,3,22,29,26,15,0
};
int sum=0,N=0;
void L(char *TABLE[31],char *K,int M)
{
int i=B[N];
while(TABLE[i])
{
sum++;
if(TABLE[i]==K) return;
i=(i+1)%M;
}
if(N<M-1)
{
TABLE[i]=K;
N++;
return;
}
return;
}
int main(){
char *A[30]={
"THE","OF","AND","TO","A",
"IN","THAT","IS","WAS","HE",
"FOR","IT","WITH","AS","HIS",
"ON","BE","AT","BY","I",
"THIS","HAD","NOT","ARE","BUT",
"FROM","OR","HAVE","AN","THEY",
};
char *TABLE[31]={"\0"};
int i;
for(i=0;i<30;i++){
L(TABLE,A[i],31);
}
for(i=0;i<31;i++){
if(TABLE[i])
printf("%d:%s\n",i,TABLE[i]);
else
printf("%d:NULL\n",i);
}
N=0;
sum=0;
for(i=0;i<30;i++){
L(TABLE,A[i],31);
N++;
}
printf("\n平均查找长度为%f",(float)sum/30);
}
中序遍历:
0:
1:A
2:WITH
3:ON
4:BUT
5:WAS
6:THIS
7:IN
8:BE
9:OF
10:THAT
11:AND
12:I
13:HE
14:HAD
15:OR
16:HAVE
17:AN
18:AS
19:HIS
20:THEY
21:AT
22:NOT
23:ARE
24:FROM
25:THE
26:IS
27:TO
28:FOR
29:IT
30:BY
平均查找长度为3.600000