To find an element using the hash algorithm:
/* Hash search, using rehash method if Find K, return if not find, d= (d+step)%m, rehash find */int Searchhash (hash Table 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[] = {%, n, a, a, 123, a, 342, and all}; 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;}
Output Result:
[Email protected]:/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, ke Y=342[LINE:70] Di:8, i=7, key=90hash index: 0 1 2 3 4 5 6 7 8 9 10 Key value: -1 123 342- 1 -1 Hash Times: 0 1 1 3 4 4 1 7 7 0 0
Finding elements using the hash algorithm