HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Understanding of hash tables

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
understandingtableshash

Problem

I am currently studying hash tables in an introductory course to computer science. I was taught that hash table is a data structure that associates a key to an index (a hash table) and then to the value associated to the key.

I don't understand why the hash function doesn't directly associate the key to the value

Solution

You cannot associate the key to a value directly, since you don't know in advance the set of keys. Hash tables implement an associative array, which is indexed by arbitrary objects. A naive implementation would have a huge array, indexed by all possible values of all possible types of objects. But this is clearly not realistic. Hash tables instead use a hash function to map a key to a numeric index, which is then used to address a conventional array.

If you knew the set of keys in advance, you could implement associative arrays as arrays indexed by the keys (like your suggestion). But it is not clear how to implement this. Suppose, for example, that the keys are all 3-regular graphs on 10 vertices. Given a 3-regular graph on 10 vertices, how do you associate it to a position in your array? It's not clear how to do this efficiently. Using a hash function, however, this becomes very easy.

Context

StackExchange Computer Science Q#69256, answer score: 3

Revisions (0)

No revisions yet.