Kodewick
Start learning →
Open addressing17 / 50

Open addressing

Lesson 17 of 50 · Part 4 · Hash tables · about 17 minutes

Open addressing handles a collision by looking further along the same table for an empty slot, as in linear probing's (k % M + i) % M; it slows sharply as the table fills (about 47 probes for a failed search at load factor 0.9), and deleting needs a tombstone.

Last lesson said collisions can't be avoided: with a table of 11, both 22 and 33 compute slot 0. The cheapest fix is to use no extra space: find another empty slot in the same table, and when searching, follow the same route. That's open addressing. It uses a single array and is cache-friendly; Python's dict and many high-performance hash tables use it. It also has two traps: it slows down sharply once the table fills, and you can't delete carelessly. This lesson runs each one for real.

Linear probing: one slot at a time

Try number i goes to (h(k) + i) % m, for i = 0, 1, 2…: if the home slot is taken, look at the next one, wrapping from the end back to 0. Each look is a probe. Table size 11, h(k) = k % 11, inserting 22 41 53 46 30 13 1 67 in order:

indexes 0 to 10, h(k) = k % 11012345678910

Linear probing: if a slot is taken, look at the next one, until an empty slot turns up

Searching follows the same route: compute h(k); if it's k, found; if it's some other key, look at the next slot; an empty slot means k isn't in the table, because inserting k would have stopped at the first empty slot on this route. Finding 67 takes 4 comparisons, finding 30 takes 3.

Guess the outputA wrong guess is fine

7 18 29 40 all have k % 11 = 7. Then 51 goes in: which slot does it land in, after how many probes? (It prints "slot probes".)

1#include <stdio.h>2 3#define M 114int t[M];5 6int insert(int k) {             // returns the number of probes7    for (int i = 0; i < M; i++) {8        int p = (k % M + i) % M;9        if (t[p] == -1) { t[p] = k; return i + 1; }10    }11    return -1;12}13 14int main(void) {15    for (int i = 0; i < M; i++) t[i] = -1;16    insert(7); insert(18); insert(29); insert(40);17    int n = insert(51);18    for (int i = 0; i < M; i++)19        if (t[i] == 51) printf("%d %d\n", i, n);20    return 0;21}
Choose one

With this stage's 8 keys in place (slots 0–4 hold 22 1 46 13 67, slots 5–7 are empty, slots 8–10 hold 41 53 30), how many slots does a search for 12 look at before it knows 12 isn't there?

Exercise 1

Inserting with linear probing

Fill in insert: starting at k % M, look for the first empty slot (-1), wrapping from the end back to 0. After inserting, the whole table is printed, with _ for an empty slot.

It should print
_ _ 41 _ _ 18 44 59 32 22 31 73 _ 
exercise1.c
1#include <stdio.h>2 3#define M 134int t[M];5 6void insert(int k) {7    // i from 0 to M - 1: p = (k % M + i) % M; if t[p] == -1, put it there and return8}9 10int main(void) {11    int keys[] = {18, 41, 22, 44, 59, 32, 31, 73};12    for (int i = 0; i < M; i++) t[i] = -1;13    for (int i = 0; i < 8; i++) insert(keys[i]);14    for (int i = 0; i < M; i++)15        if (t[i] == -1) printf("_ "); else printf("%d ", t[i]);16    printf("\n");17    return 0;18}
Output
Press Run or Ctrl+Enter

Primary clustering: fuller means slower

Once linear probing has placed the 8 keys 22 41 53 46 30 13 1 67 (the table from this lesson's first stage), slots 0 to 4 have merged into one run. Any new key whose h lands anywhere in 0 to 5 will stop at slot 5, so slot 5 gets picked with probability 6 / 11, while each other empty slot has 1 / 11. The longer a run, the more likely it catches the next key, and the longer it grows. This is primary clustering, linear probing's weakness: keys with different h end up in the same run, slowing each other down.

Quadratic probing spreads the steps out: tries 1, 2, 3, 4… go to h + 1², h − 1², h + 2², h − 2²… (all % m). The same 8 keys:

indexes 0 to 10, h(k) = k % 1122464153012345678910

Quadratic probing: if taken, try +1, −1, +4, −4…, instead of crowding in slot by slot

Two keys with the same h still follow the same route under quadratic probing (that's called secondary clustering), but keys with different h no longer queue along the same run. To see how much it matters, run it on a table of 1019 slots: insert random keys and measure the average number of probes, separately for a successful search (a key in the table) and a failed one (a key not in it).

main.c
1#include <stdio.h>2 3#define M 1019                  // a prime with M % 4 == 3: quadratic probing can reach every slot4unsigned table[M];5char used[M];6unsigned seed = 1;7 8unsigned next_key(void) {       // a home-made pseudo-random generator: the same every run, never repeats9    seed = seed * 1664525u + 1013904223u;10    return seed;11}12 13// where probe number i goes: linear = 1 is linear, otherwise quadratic (h, h+1, h-1, h+4, h-4 …)14int probe(unsigned k, int i, int linear) {15    long h = k % M;16    if (linear) return (h + i) % M;17    long d = (long)((i + 1) / 2) * ((i + 1) / 2);18    if (i % 2 == 0) d = -d;19    return (int)(((h + d) % M + M) % M);20}21 22int search(unsigned k, int linear) {      // returns how many slots it looked at (the empty one counts)23    for (int i = 0; ; i++) {24        int p = probe(k, i, linear);25        if (!used[p] || table[p] == k) return i + 1;26    }27}28 29void insert(unsigned k, int linear) {30    for (int i = 0; ; i++) {31        int p = probe(k, i, linear);32        if (!used[p]) { used[p] = 1; table[p] = k; return; }33    }34}35 36int main(void) {37    double as[] = {0.5, 0.7, 0.8, 0.9};38    printf("load  linear:found  linear:missing  quad:found  quad:missing\n");39    for (int t = 0; t < 4; t++) {40        double r[4];41        for (int linear = 1; linear >= 0; linear--) {42            for (int i = 0; i < M; i++) used[i] = 0;43            seed = 1;44            int n = (int)(as[t] * M);45            for (int i = 0; i < n; i++) insert(next_key(), linear);46            long ok = 0, fail = 0;47            seed = 1;48            for (int i = 0; i < n; i++) ok += search(next_key(), linear);49            for (int i = 0; i < 1000; i++) fail += search(next_key(), linear);  // these aren't in the table50            r[linear ? 0 : 2] = (double)ok / n;51            r[linear ? 1 : 3] = fail / 1000.0;52        }53        printf("%.1f     %6.2f        %6.2f        %6.2f       %6.2f\n", as[t], r[0], r[1], r[2], r[3]);54    }55    return 0;56}
Output
load  linear:found  linear:missing  quad:found  quad:missing
0.5       1.42          2.52          1.39         2.34
0.7       2.36          6.24          1.95         4.12
0.8       3.03         12.28          2.34         6.21
0.9       5.79         47.53          3.05        12.99

As α goes from 0.5 to 0.9, a failed search under linear probing climbs from 2.52 to 47.53 probes, nearly 20 times as many; quadratic probing only reaches 12.99. In theory a failed linear-probing search takes about ½(1 + 1 / (1 − α)²) probes, 50.5 at α = 0.9, close to what we measured; the nearer α gets to 1, the steeper it shoots up. So an open-addressing table must not get too full: α is usually kept between 0.5 and 0.75.

MethodProbe number iWeakness
Linear probingh + iPrimary clustering: long runs, slower as it fills
Quadratic probingh + 1², h − 1², h + 2², h − 2²…May not reach every slot; needs m to be a prime of the form 4j + 3
Double hashingh + i × h₂(k)Needs a second hash function, and h₂(k) must not be 0
Choose one

Table size 11, quadratic probing, and a key with h(k) = 8. Which slots do the first 4 tries look at, in order?

Choose one

Running this stage's program for real: as the load factor goes from 0.5 to 0.9, how do the average probes for a failed search with linear probing change, roughly?

Deleting needs a tombstone

Take the linear-probing table again, with 22 41 53 46 30 13 1 67 placed in turn, and delete 53. The obvious idea is to empty slot 9, but 30 got to slot 10 by passing through slot 9:

indexes 0 to 10221461367415330012345678910

The wrong way: empty slot 9 and 30 can no longer be found; a tombstone is the right way

So every slot has three states: empty, holding a key, and deleted. A search treats a tombstone as occupied and keeps going; an insert may reuse it. Lots of tombstones slow searches down too (each one still has to be walked past), so when there are too many, the whole table gets rebuilt.

main.c
1#include <stdio.h>2 3#define M 114#define EMPTY -15#define DEL   -2                // a tombstone6int t[M];7 8int search(int k) {             // returns the slot if found, -1 if not9    for (int i = 0; i < M; i++) {10        int p = (k % M + i) % M;11        if (t[p] == EMPTY) return -1;        // an empty slot: it can't be further on12        if (t[p] == k) return p;             // tombstones and other keys: keep going13    }14    return -1;15}16 17void insert(int k) {18    if (search(k) >= 0) return;              // already there19    for (int i = 0; i < M; i++) {20        int p = (k % M + i) % M;21        if (t[p] == EMPTY || t[p] == DEL) { t[p] = k; return; }   // a tombstone can be reused22    }23}24 25void remove_plain(int k) { int p = search(k); if (p >= 0) t[p] = EMPTY; }  // wrong26void remove_tomb(int k)  { int p = search(k); if (p >= 0) t[p] = DEL; }    // right27 28void build(void) {29    int keys[] = {22, 41, 53, 46, 30, 13, 1, 67};30    for (int i = 0; i < M; i++) t[i] = EMPTY;31    for (int i = 0; i < 8; i++) insert(keys[i]);32}33 34int main(void) {35    build();36    for (int i = 0; i < M; i++)37        if (t[i] == EMPTY) printf("_ "); else printf("%d ", t[i]);38    printf("\n");39    remove_plain(53);40    printf("after just emptying the slot, find 30: %d\n", search(30));41    build();42    remove_tomb(53);43    printf("after leaving a tombstone, find 30: %d\n", search(30));44    insert(75);                              // 75 % 11 = 9: reuses the tombstone's slot45    printf("insert 75: it's in slot %d\n", search(75));46    return 0;47}
Output
22 1 46 13 67 _ _ _ 41 53 30 
after just emptying the slot, find 30: -1
after leaving a tombstone, find 30: 10
insert 75: it's in slot 9

In exams: "linear probing causes clustering (piling up)" and "deleting from an open-addressing table can't just empty the slot; it can only mark it deleted (lazy deletion)" are common multiple-choice points. Quadratic probing's increments are 1², −1², 2², −2²…, which needs the table length to be a prime of the form 4j + 3. For draw-the-table questions, insert the keys one by one in order and write each key's probe count beside it; the patterns lesson at the end of this chapter uses those counts to compute the ASL.

Choose one

After deleting with tombstones, which statement is true?

Guess the outputA wrong guess is fine

3, 10 and 17 all leave remainder 3; linear probing put them in slots 3, 4 and 5. First 3 is deleted with a tombstone, then 24 is inserted (24 % 7 = 3). What does the program print?

1#include <stdio.h>2 3#define M 74#define EMPTY -15#define DEL -26int t[M] = {EMPTY, EMPTY, EMPTY, 3, 10, 17, EMPTY};7 8int search(int k) {9    for (int i = 0; i < M; i++) {10        int p = (k % M + i) % M;11        if (t[p] == EMPTY) return -1;12        if (t[p] == k) return p;13    }14    return -1;15}16 17void insert(int k) {18    for (int i = 0; i < M; i++) {19        int p = (k % M + i) % M;20        if (t[p] == EMPTY || t[p] == DEL) { t[p] = k; return; }21    }22}23 24int main(void) {25    t[search(3)] = DEL;26    insert(24);27    printf("%d %d\n", search(24), search(17));28    return 0;29}
Exercise 2

A search that steps over tombstones

In this table -1 is an empty slot and -2 a tombstone. Fill in search: at an empty slot return -1; at k return the slot; at a tombstone or any other key keep going.

It should print
10 4 -1 -1
exercise2.c
1#include <stdio.h>2 3#define M 114int t[M] = {22, 1, 46, 13, 67, -1, -1, -1, 41, -2, 30};   // 53 was deleted, leaving a tombstone5 6int search(int k) {7    // i from 0 to M - 1: p = (k % M + i) % M; empty: return -1; k: return p8    return -1;9}10 11int main(void) {12    printf("%d %d %d %d\n", search(30), search(67), search(53), search(19));13    return 0;14}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Open addressing: on a collision, find another slot in the table

  • Linear probing h + i: simple, but builds long runs (primary clustering)
  • Quadratic probing h ± i²: jumps away, far less clustering
  • Fuller is slower: at α = 0.9 a failed linear search takes about 47 probes; keep α under 0.75
  • Delete with a tombstone: searches step over it, inserts may reuse it
1for (int i = 0; i < M; i++) {2    int p = (k % M + i) % M;3    if (t[p] == EMPTY) return -1;4    if (t[p] == k) return p;5}