試圖使用smdb算法做一個哈希表(因爲我聽到這是明智的,不要試圖寫我自己的。)我敢肯定,我是完全錯誤的。我提到我是C新手嗎?C smdb散列值%tableSize重複計算爲相同的值? (用不同的輸入。)
我的hashFunction()%size在第一次調用時返回一個數字,如35,然後在第二次調用,第三次調用,第四次調用時返回65,並返回65。我只是將這些數字用作任意的例子。試圖用調試器來弄明白後,我發現散列函數將返回不同的多頭,但它們使用相同的最後2個數字全部結束......像這樣......
4460735 4526335 4591935
所以我想這是爲什麼當我散列%大小時,每次都會得到相同的輸出結果。這違背了均勻分佈鍵的想法,對吧?
請隨便找我。我知道SO上的野蠻人可以如何。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char* str;
struct node* next;
}
node;
void insertItem(char* number, node** list);
unsigned long hashFunction(char* str);
int main(void)
{
int size = 100;
int index = 0;
node* buckets[size];
for (int i = 0; i < size; i++)
{
char c = i + 'A';
index = hashFunction(&c) % size;
insertItem(&c, &buckets[index]);
}
}
void insertItem(char* str, node** list)
{
node* newItem = malloc(sizeof(node));
newItem->str = str;
newItem->next = *list;
*list = newItem;
}
unsigned long hashFunction(char* str)
{
//sdbm hash function adapted (incorrectly?) from here: http://www.cse.yorku.ca/~oz/hash.html
unsigned long hash = 0;
int c;
while ((c = *str++))
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
也許使用質數作爲'size'可以幫助:http://stackoverflow.com/q/3980117/1025391/HTTP:// stackoverflow.com/q/1145217/1025391? – moooeeeep
啊 - 這不是真正的問題。現在我看... – moooeeeep
@moooeeeep感謝您的提示,但!我以前讀過,你說得對,我會在將來考慮。 –