hash function for text in C

Scott C. Mac Phee macphee at convex.COM
Wed Oct 17 22:47:59 AEST 1990


In article <1990Oct16.184951.513 at watdragon.waterloo.edu> cpshelley at violet.waterloo.edu (cameron shelley) writes:
>
>  I have been (futily :<) experimenting with hash functions to 
>hash english words into a large array.  No book I can find around
>here gives the topic more than cursory discussion.  Does anyone
>out there know of a good, simple one?  They must exist, and I'm
>getting a little tired of mine... (er, function that is, I can't
>afford another data structures book right now :).

Here is some code I've been using.  It is an adapted version of some
hashing algorithms I've seen pass through this newsgroup.

Hope it helps...

===========================================================================

/*
 * ============================================================================
 *                     HASH TABLE FUNCTIONS
 * ============================================================================
 */

#define HASH_TABLE_SIZE 1000
static	int	eventhash[HASH_TABLE_SIZE] ;
static	int	hash_entries,			/* number in table...	*/
		collisions ;			/* count of collisions	*/

int
init_hash_table()
{
register int i ;

    hash_entries = collisions = 0 ;

    for (i=0; i<HASH_TABLE_SIZE;) eventhash[i++] = 0 ;

}

/*
 * calc_hash_value.c
 *
 * calculate a hash table location from the given name.
 *
 */

int
calc_hash_value(name)
char    *name ;
{
register    int hash ;

    for (hash=0; *name;)
        hash = (hash<<2) ^ *name++ ;

    return(abs(hash % HASH_TABLE_SIZE)) ;

}


--
===============================================================================
CONVEX Computer Corporation (CVX)                  Richardson, Texas
Scott C. Mac Phee (..uunet.uu.net!convex.com!macphee)   214-497-4772
===============================================================================



More information about the Comp.lang.c mailing list