散列表

Hash Tables

Use BST and red-black BST to implement symbol tables could achieve average ∼lg⁡N\sim \lg{N} cost per operation. But with different access to the data, we could do better.

The basic plan is to save items in a key-indexed table (index is a function of the ley).

Hash function. Method for computing array index from key.

Issues.

  • Efficiently computing the hash function.
  • Equality test: Method for checking whether two keys are equal.
  • Collision resistance: Algorithm and data structure to handle two keys that hash to the same array index.

Hash Functions

Use hashCode() to get hash values. View Java 配套笔记 on how to implement hashCode() for user-defined type.

Note that hashCode() returns an int between −231-2^{31} and 231−12^{31}-1; but what we need is an int between 00 and M−1M-1 (for use as array index).

java
private int hash(Key key) {
    return (key.hashCode() & 0x7fffffff) % M;
    // M is typically a prime or power of 2
}

The efficiency of hash tables is based on the uniform hashing assumption.

Uniform hashing assumption. Each key is equally likely to hash to an integer between 00 and M−1M-1.

Collision Resolutions

Collision. Two distinct keys hashing to the same index.

Two kinds of symbol tables could effiiciently handle collision under uniform hashing assumption.

  • Separate chaining symbol table.
  • Linear probing symbol table.

Separate chaining ST. Use an array of M<NM<N linked lists.

  • Hash: map key to interger ii between 00 and M−1M-1.
  • Insert: put at front of the i-th chain (if not already there).
  • Search: need to search only i-th chain.
java
public Value get(Key key) {
    int i = hash(key);
    for (Node x = st[i]; x != null; x = x.next)
        if (key.equals(x.key))	return (Value) x.val;
    return null;
}

public void put(Key key, Value val) {
    int i = hash(key);
    for (Node x = st[i]; x != null; x = x.next)
        if (key.equals(x.key))  { x.val = val; return; }
    st[i] = new Node(key, val, st[i]);	// insert at front
}

Consequence. Number of probes (equals() and hashCode()) for search/insert is proportional to N/MN/M. It is MM times faster than sequential search.

  • MM too large →\to too many empty chains.
  • MM too small →\to chains too long.
  • Typical choice: M∼N/5M\sim N/5 →\to constant-time ops.

Linear probing ST. (open addressing) When a new key collides, find next empty slot, and put it there.

  • Hash. Map key to integer ii between 00 and M−1M-1.
  • Insert. Put at table index ii if free; if not try i+1i+1, i+2i+2, etc.
  • Search. Search table index ii; if occupied but no match, try i+1i+1, i+2i+2, etc.

Note that array size MM must be greater than number of key-value pairs NN.

java
public Value get(Key key) {
	for (int i = hash(key); keys[i] != null; i = (i+1) % M)
        if (key.equals(keys[i]))	return vals[i];	// search hit
    return null;	// search miss
}

public void put(Key key, Value val) {
    int i;
    for (i = hash(key); keys[i] != null; i = (i+1) % M)
        if (keys[i].equals(key))	break;
    keys[i] = key;
    vals[i] = val;
}

Proposition. Under uniform hashing assumption, the average # of probes in a linear probing hash table of size MM that contains N=αMN=\alpha M keys is: ∼12(1+11−α)\sim \frac{1}{2}(1+\frac{1}{1-\alpha}) for a search hit; ∼12(1+1(1−α)2)\sim \frac{1}{2}(1+\frac{1}{(1-\alpha)^2}) for a search miss/insert/delete.

  • MM too large →\to too many empty array entries.
  • MM too small →\to clustering happens. search time blows up.
  • Typical choice: [half full] α=N/M∼1/2\alpha=N/M\sim 1/2.
    • # probes for search hit is about 3/23/2.
    • # probes for search miss is about 5/25/2.

The deletion in linear-probing ST is a bit tricky.

  • Tombstones.
  • Reinsert all of the key-value pairs in the same cluster appeared after the deleted key-value pair.

Hash Tables vs. BST

Note the efficiency of hash table depends on uniform hashing assumption

Hash tables.

  • Simplier to code.
  • No effective alternative for unordered keys.
  • Faster for simple keys in practice (a few arithmetic ops versus log⁡N\log{N} compares).

Balanced search trees.

  • Stronger performance guarantee. (Hash tables need uniform hashing assumption)
  • Support for ordered ST operations.
  • Easier to implement compareTo() correctly than equals() and hashCode().

Java system includes both implementation:

  • Red-black BSTs: java.util.TreeMap, java.util.TreeSet.
  • Hash tables: java.util.HashMap, java.util.IdentityHashMap.
CC BY-NC-SA 4.0
正在加载评论…