C语言哈希查找

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#define MAXKEY 1000
typedef struct Info_s {
	int num;
	char name[30];
	int age;
	char addr[30];
}Info_t, *pInfo_t;
//哈希函数
int hash(char *key)
{
	int h = 0, g;
	while (*key)
	{
		h = (h << 4) + *key++;
		g = h & 0xf0000000;
		if (g)
			h ^= g >> 24;
		h &= ~g;
	}
	return h % MAXKEY; //返回值范围: 0~MAXKEY-1
}
int main() {
    //建立哈希表
	pInfo_t hashTable[MAXKEY] = { NULL };
	Info_t infoArr[] = {
		1001, "Wuyifan", 30, "Canada",
		1003, "Liuhuaqiang", 45, "Shijiazhuang",
		1005, "Zhengshuang", 30, "Shenyang",
		1007, "Mayun", 50, "Hangzhou"
	};
    //准备好的数据插入哈希表
	for (int i = 0; i < sizeof(infoArr) / sizeof(Info_t); ++i) {
		int hashValue = hash(infoArr[i].name);
		hashTable[hashValue] = &infoArr[i];
	}
    //查找
	char name[30];
	while (scanf("%s", name) != EOF) {
		if (hashTable[hash(name)] == NULL) {
			printf("%s is not in array!\n", name);
		}
		else {
			printf("%d %s %d %s\n", 
				hashTable[hash(name)]->num,
				hashTable[hash(name)]->name,
				hashTable[hash(name)]->age,
				hashTable[hash(name)]->addr);
		}
	}
}

你可能感兴趣的:(C++,哈希算法,c语言,散列表)