Sunday, August 13, 2017

Hashing

  • 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 % HASHSIZE from 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" type unsigned long instead of the simple unsigned (int).
    unsigned hash(char *s)
    {
        unsigned hashval;
    
        for (hashval = 0; *s != '\0'; s++)
            hashval = *s + 31*hashval;
        return hashval % HASHSIZE;
    }

No comments:

Post a Comment