Zi 字媒體
2017-07-25T20:27:27+00:00
C語言-雜湊表(Hash table,也叫哈希表)-沒有資料庫又要快速搜尋的資料結構演算法
雜湊表(Hash table,也叫哈希表),是根據鍵(Key)而直接查詢在內存存儲位置的資料結構。也就是說,它通過計算一個關於鍵值的函數,將所需查詢的數據映射到表中一個位置來查詢記錄,這加快了查找速度。這個映射函數稱做雜湊函數,存放記錄的數組稱做雜湊表。
一個通俗的例子是,為了查找電話簿中某人的號碼,可以創建一個按照人名首字母順序排列的表(即建立人名 {\displaystyle x} x到首字母 {\displaystyle F(x)} F(x)的一個函數關係),在首字母為W的表中查找「王」姓的電話號碼,顯然比直接查找就要快得多。這裡使用人名作為關鍵字,「取首字母」是這個例子中雜湊函數的函數法則 {\displaystyle F()} F(),存放首字母的表對應雜湊表。關鍵字和函數法則理論上可以任意確定。
資料來源:https://zh.wikipedia.org/wiki/哈希表
https://blog.csdn.net/smstong/article/details/51145786
https://mp.weixin.qq.com/s?__biz=MzI2NjA3NTc4Ng==&mid=2652081098&idx=1&sn=fbf7d3021ed17bedc8eb62bc997bedc3&chksm=f174802fc6030939686549d596d27a1d90fec683afdcf0fb59934f5ee3131f3cba92e39d12e1&scene=0&xtrack=1&key=a6e428af7bc20b4ec1d88814f483cd8573327a2a636d2d8ee0db8f4b4881aaba847e7f578053a0136c95477a6428492b832966015bcff77cd33b5b339c7fc803dbcebc8f549e536facfa6f80c55e7822&ascene=1&uin=MjIwODk2NDgxNw==&devicetype=Windows+10&version=62060833&lang=zh_TW&pass_ticket=n+ryKuocjshj/viC/QR8cPIy2PXfuyFlk35RNGNb3ZSMIZrIoRZKr7lcuiC9DOlK
GITHUB: https://github.com/jash-git/C_HashTable
#include
#include
#include "HashTable.h"
// 出處 https://blog.csdn.net/smstong/article/details/51145786
// 要放入哈希表中的结构体
struct Student
{
int age;
float score;
char name[32];
char data[1024 * 1024* 10];
};
// 结构体内存释放函数
static void free_student(void* stu)
{
free(stu);
}
// 显示学生信息的函数
static void show_student(struct Student* p)
{
printf("name:%s, age:%d, credit:%.2f\n", p->name, p->age, p->score);
}
void pause()
{
printf("Press Enter key to continue…");
fgetc(stdin);
}
int main()
{
// 新建一个HashTable实例
HashTable* ht = hash_table_new();
if (NULL == ht) {
return -1;
}
// 向哈希表中加入多个学生结构体
int i=0;
for (i = 0; i < 100; i++)
{
struct Student * stu = (struct Student*)malloc(sizeof(struct Student));
stu->age = 18 + rand()%5;
stu->score = 50.0f + rand() % 100;
sprintf(stu->name, "Classmate%d", i);
hash_table_put2(ht, stu->name, stu, free_student);
}
// 根据学生姓名查找学生结构
for (i = 0; i < 100; i++)
{
char name[32];
sprintf(name, "Classmate%d", i);
struct Student * stu = (struct Student*)hash_table_get(ht, name);
show_student(stu);
}
// 销毁哈希表实例
hash_table_delete(ht);
pause();
return 0;
}
寫了
5860316篇文章,獲得
23313次喜歡