Example 1 — Rehash while inserting 1 to 7
Start with four slots and linear probing.
#include <stdio.h>
#include <stdlib.h>
#define EMPTY (-1)
struct Set { int *slot; int cap, count; };
static int *make(int cap) {
int *a = malloc(cap * sizeof *a);
if (!a) exit(1);
for (int i = 0; i < cap; i++) a[i] = EMPTY;
return a;
}
static void place(int *slot, int cap, int key) {
int i = key % cap;
while (slot[i] != EMPTY) i = (i + 1) % cap;
slot[i] = key;
}
static void add(struct Set *s, int key) {
place(s->slot, s->cap, key);
s->count++;
if ((double)s->count / s->cap > 0.75) {
int newcap = s->cap * 2;
int *ns = make(newcap);
for (int i = 0; i < s->cap; i++)
if (s->slot[i] != EMPTY) place(ns, newcap, s->slot[i]);
printf("rehash at key %d: capacity %d -> %d\n", key, s->cap, newcap);
free(s->slot);
s->slot = ns;
s->cap = newcap;
}
}
int main(void) {
struct Set s = {make(4), 4, 0};
for (int k = 1; k <= 7; k++) add(&s, k);
printf("final: count=%d capacity=%d load=%.2f\n",
s.count, s.cap, (double)s.count / s.cap);
free(s.slot);
return 0;
} How It Works
- With four slots, the fourth key makes the load 1.0, which exceeds 0.75.
- All keys are reinserted into the 8-slot table, where
key % 8gives new slots. - At the seventh key the load is 0.875, so the table doubles to 16, giving a final load of 0.4375.
