今天又完成了一道編程題。此題是用線性探測再散列解決衝突的雜湊表設計題。
完成後還是有些困惑,發現自己對演算法分析不是特理解。例如,“平均尋找長度的上限為2”就不是特別理解。
雖然演算法寫完了,但是效能不知道有沒有題中所說的那樣“平均尋找長度的上限為2”呢?
希望懂的GG,MM幫忙看下~哦
/*
作者:徐**
日期:12.29 918
Version:v1.0
作用:為班級30個人設計一個Hash表,要求
用除留餘數數法構造Hash表,用線性探測再
散列法處理衝突,平均尋找長度的上限為2
*/
#include <stdio.h>
#include <string.h>
#define MAX 50
#define STU_MAXNUM 30
#define NULLKEY -1
typedef int KeyType;
typedef struct
{
KeyType key_num;
char name[30];
}RecordType;
typedef RecordType HashTable[MAX];
void Init(HashTable ht)
{
int i;
for(i = 0; i < MAX; i++)
{
ht[i].key_num = NULLKEY;
}
}
int Hash(int key)
{
int mode = key % 13;
return mode;
}
int InsertHash(HashTable ht, RecordType record)
{
int p0 = Hash(record.key_num);
if(ht[p0].key_num == NULLKEY)
{
ht[p0].key_num = record.key_num;
strcpy(ht[p0].name, record.name);
}
else //如果發生衝突,則用線性探測再散列解決衝突
{
int i, pi;
for(i = 1; i <= MAX - 1; i++)
{
pi = (p0 + i) % MAX;
if(ht[pi].key_num == NULLKEY)
{
ht[pi].key_num = record.key_num;
strcpy(ht[pi].name, record.name);
}
}
}
return 1;
}
int Hash_Create(HashTable ht)
{
int count = 0;
RecordType record;
for(count = 0; count < STU_MAXNUM; count++) //產生STU_MAXNUM(30)個學生的記錄
{
memset(&record, 0x00, sizeof(record));
printf("Please input a key_num of student : ");
scanf("%d", &(record.key_num));
getchar();
printf("Please input name of this student : ");
gets(record.name);
InsertHash(ht, record);
}
printf("/nCreate Successfully!/n");
return 1;
}
int Hash_Search(HashTable ht, int key)
{
int p0;
p0 = Hash(key);
if(ht[p0].key_num == NULLKEY) return NULLKEY; //如果為空白索引值,則表示尋找失敗
else if(ht[p0].key_num == key) return p0;
else //用線性探測再散列法解決衝突
{
int i;
int pi;
for(i = 1; i <= MAX - 1; i++)
{
pi = (p0 + 1) % MAX;
if(ht[pi].key_num == NULLKEY) return NULLKEY;
else if(ht[pi].key_num == key) return pi;
}
}
return NULLKEY;
}
int main()
{
int key = NULLKEY;
HashTable ht;
Init(ht);
Hash_Create(ht);
printf("Please input the key you want Search : ");
scanf("%d", &key);
key = Hash_Search(ht, key);
if(key != NULLKEY)
{
printf("key_num : %d/nname : %s/n", ht[key].key_num, ht[key].name);
}
return 0;
}