String hash function
- Recall that the Java String function combines successive characters by multiplying the current hash by 31 and then adding on the new character.
int hash = 0; for (int i = 0; i < length(); i++) { hash = 31 * hash + charAt(i); } return hash; - Probably a pretty decent hash algorithm, as presented in K&R version 2 (verified by me on pg. 144 of the book); NB: be sure to remove
% HASHSIZEfrom the return statement if you plan on doing the modulus sizing-to-your-array-length outside the hash algorithm. Also, I recommend you make the return and "hashval" typeunsigned longinstead of the simpleunsigned(int).unsigned hash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31*hashval; return hashval % HASHSIZE; }
Sunday, August 13, 2017
Hashing
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment