使用再哈希算法查找元素:
/* hash search, using rehash method if find k, return if not find, d=(d+step)%m, rehash find */int SearchHash(HashTable H, KeyType k){ int d, d1, m; m = H.tableSize; d = d1 = k%m; while(H.data[d].key != -1) { if(H.data[d].key == k) //hunt return d; else d = (d+1)%m; if(d==d1) return -1; //fail } return -1;}
int main(int argc, char *argv[]){ int hash[] = {23, 35, 12, 56, 123, 39, 342, 90}; int m=11, p=11, n=8, pos; int key, index; HashTable H; CreateHash(&H, m, p, hash, n); key = 123; index = SearchHash(H, key); if(index < 0) { printf("find failed!\n"); return -1; } printf("key:%d, index:%d\n", key, index); return 0;}输出结果:
root@ubuntu:/mnt/shared/appbox/hash# ./hash[line:59] addr:1, i=0, key=23[line:59] addr:2, i=1, key=35[line:70] di:3, i=2, key=12[line:70] di:4, i=3, key=56[line:70] di:5, i=4, key=123[line:59] addr:6, i=5, key=39[line:70] di:7, i=6, key=342[line:70] di:8, i=7, key=90hash index: 0 1 2 3 4 5 6 7 8 9 10 key value: -1 23 35 12 56 123 39 342 90 -1 -1 hash times: 0 1 1 3 4 4 1 7 7 0 0 key:123, index:5root@ubuntu:/mnt/shared/appbox/hash#