This file contains (part of) the code from "Algorithms in C, Third Edition, Parts 1-4," by Robert Sedgewick, and is covered under the copyright and warranty notices in that book. Permission is granted for this code to be used for educational purposes in association with the text, and for other uses not covered by copyright laws, provided that the following notice is included with the code: "This code is from "Algorithms in C, Third Edition," by Robert Sedgewick, Addison Wesley Longman, 1998." Commercial uses of this code require the explicit written permission of the publisher. Send your request for permission, stating clearly what code you would like to use, and in what specific way, to: aw.cse@aw.com CHAPTER 14. Hashing ----- int hash(char *v, int M) { int h = 0, a = 127; for (; *v != '\0'; v++) h = (a*h + *v) % M; return h; } ----- int hashU(char *v, int M) { int h, a = 31415, b = 27183; for (h = 0; *v != '\0'; v++, a = a*b % (M-1)) h = (a*h + *v) % M; return h; } ----- static link *heads, z; static int N, M; void STinit(int max) { int i; N = 0; M = max/5; heads = malloc(M*sizeof(link)); z = NEW(NULLitem, NULL); for (i = 0; i < M; i++) heads[i] = z; } Item STsearch(Key v) { return searchR(heads[hash(v, M)], v); } void STinsert(Item item) { int i = hash(key(item), M); heads[i] = NEW(item, heads[i]); N++; } void STdelete(Item item) { int i = hash(key(item), M); heads[i] = deleteR(heads[i], item); } ----- #include #include "Item.h" #define null(A) (key(st[A]) == key(NULLitem)) static int N, M; static Item *st; void STinit(int max) { int i; N = 0; M = 2*max; st = malloc(M*sizeof(Item)); for (i = 0; i < M; i++) st[i] = NULLitem; } int STcount() { return N; } void STinsert(Item item) { Key v = key(item); int i = hash(v, M); while (!null(i)) i = (i+1) % M; st[i] = item; N++; } Item STsearch(Key v) { int i = hash(v, M); while (!null(i)) if eq(v, key(st[i])) return st[i]; else i = (i+1) % M; return NULLitem; } ----- void STdelete(Item item) { int j, i = hash(key(item), M); Item v; while (!null(i)) if eq(key(item), key(st[i])) break; else i = (i+1) % M; if (null(i)) return; st[i] = NULLitem; N--; for (j = i+1; !null(j); j = (j+1) % M, N--) { v = st[j]; st[j] = NULLitem; STinsert(v); } } ----- void STinsert(Item item) { Key v = key(item); int i = hash(v, M); int k = hashtwo(v, M); while (!null(i)) i = (i+k) % M; st[i] = item; N++; } Item STsearch(Key v) { int i = hash(v, M); int k = hashtwo(v, M); while (!null(i)) if eq(v, key(st[i])) return st[i]; else i = (i+k) % M; return NULLitem; } ----- void expand(); void STinsert(Item item) { Key v = key(item); int i = hash(v, M); while (!null(i)) i = (i+1) % M; st[i] = item; if (N++ > M/2) expand(); } void expand() { int i; Item *t = st; init(M+M); for (i = 0; i < M/2; i++) if (key(t[i]) != key(NULLitem)) STinsert(t[i]); free(t); } ----------