Hash table insertion
What you'll learn: How to map a key to an index and store data inside a hash table array.
The Library Analogy
Imagine a massive library with thousands of books. If you store them randomly, you have to search every shelf to find one specific title. If you store them alphabetically, you still have to browse the "S" section for a while to find "Shakespeare."
A Hash Table works like a magic librarian. When you hand them a book title, they run a quick calculation and tell you, "That goes exactly on Shelf #42." Insertion is the process of using that calculation to put a piece of data in its perfect, pre-determined spot.
The Insertion Process
To insert a value (like a phone number) associated with a key (like a name), we follow three steps:
- Hash the Key: Run the name through a "Hash Function" to get a large number.
- Compress the Index: Use the modulo operator (
%) to turn that large number into a valid index within your array size. - Store the Data: Place the data at that specific array index.
Coding the Insertion
In this example, we have a simple array of Person objects. We want to insert "Alice" into our table.
#include <stdio.h>
#include <string.h>
#define TABLE_SIZE 10
typedef struct {
char name[50];
char phone[20];
} Person;
Person* hashTable[TABLE_SIZE];
// A simple hash function
unsigned int hash(char *name) {
unsigned int value = 0;
for (int i = 0; name[i] != '\0'; i++) {
value += name[i];
}
return value % TABLE_SIZE;
}
void insert(Person *p) {
// 1. Find the destination
int index = hash(p->name);
// 2. Place the person in the bucket
// (Note: This assumes the spot is empty!)
hashTable[index] = p;
printf("Inserted %s at index %d\n", p->name, index);
}
int main() {
Person alice = {"Alice", "555-0123"};
insert(&alice);
return 0;
}
Handling "Full" Spots
You might wonder: "What if two different names result in the same index?" This is called a collision. In a basic insertion, you would need a strategy (like a linked list at that index) to hold both items. For now, focus on the magic of the calculation: the hash function turns a label into a coordinate, allowing you to jump straight to the correct "shelf" without searching.
Key takeaway
Insertion uses a hash function to transform a key into a specific array index, providing near-instant storage.