Hash table lookup
What you'll learn: How to quickly retrieve a value from a hash table by transforming a key into an array index.
The library analogy
Imagine a massive library where books aren't organized by title or author, but by a "magic number." When you want to find a specific book, you don't walk through every aisle (which would be an search). Instead, you put the book's title into a special machine called a Hash Function.
The machine spits out a single number—say, 42. You go directly to Shelf 42, and there is your book. This is the power of a hash table lookup: it turns a search problem into a direct access problem, allowing you to find data almost instantly, regardless of how much data you have.
How the lookup works
In C, a hash table is usually an array of structures. To perform a lookup, we follow three specific steps:
- Hashing: We pass our search key (like a string or ID) through a hash function to get a large integer.
- Indexing: We use the modulo operator (
%) with the array size to turn that large integer into a valid array index. - Accessing: We jump straight to that index in the array and grab the data stored there.
C Implementation
Here is how a basic lookup function appears in code. We assume the hash table is an array of Entry structs.
typedef struct {
char *key;
int value;
} Entry;
// Our table is an array of entries
Entry table[100];
int lookup(char *search_key) {
// 1. Get the hash code (using a hypothetical hash function)
unsigned int hash_value = hash_function(search_key);
// 2. Map the hash to a valid index (0-99)
int index = hash_value % 100;
// 3. Return the value found at that direct location
// In a simple table, we assume the key exists at this index
return table[index].value;
}
Dealing with "Wrong House" results
In the real world, two different keys might occasionally point to the same index (a collision). A robust lookup function will check if the key stored at that index actually matches the search_key you provided. If it doesn't, the code will follow a "link" or move to the next slot to find the correct data. However, the core principle remains the same: the hash function gives you the "starting address," cutting out the need to search the entire list from the beginning.
Key takeaway
Lookup works by hashing a key to generate a direct array index, allowing for near-instant data retrieval.