Introduction to hash functions

suggest change

A hash function h() maps data x ∈ X of arbitrary size to a value y ∈ Y of fixed size: y = h(x). Good hash functions have the following properties:

In the general case the hash is smaller than the input: |y| < |x|. Hash functions are not reversible. In other words, collisions are possible: ∃ x1, x2 ∈ X, x1 ≠ x2: h(x1) = h(x2). X may be finite or infinite, and Y is finite.

Hash functions are used in a lot of parts of computer science, for example in software engineering, cryptography, databases, networks, machine learning and so on. There are many different types of hash functions, with differing domain specific properties.

Often a hash is an integer. Programming languages provide methods that calculate it. For example, in C# GetHashCode() returns an Int32 for every type. In Java every class provides hashCode(), which returns int. Each data type has its own implementation, or a user-defined one.

Hash methods

There are several approaches for determining a hash function. Without loss of generality, let x ∈ X = {z ∈ ℤ: z ≥ 0} be a non-negative integer. Often m is prime (not too close to an exact power of 2).

Method | Hash function |
—— | —— |
Division method | h(x) = x mod m | is often a good choice for m |
Multiplication method | h(x) = ⌊m (xA mod 1)⌋, A ∈ {z ∈ ℝ: 0 < z < 1} |

Hash table

Hash functions are used in hash tables to compute an index into an array of slots. A hash table is a data structure for implementing dictionaries (key-value structures). A well-implemented hash table takes O(1) expected time to insert, search, and delete by key. More than one key may hash to the same slot. There are two ways for resolving collision:

  1. Chaining: linked list is used for storing elements with the same hash value in slot
  2. Open addressing: zero or one element is stored in each slot

The next methods are used to compute the probe sequences required for open addressing

Method | Formula |
—— | —— |
Linear probing | h(x, i) = (h'(x) + i) mod m |
Quadratic probing | h(x, i) = (h'(x) + c1*i + c2*i^2) mod m |
Double hashing | h(x, i) = (h1(x) + i*h2(x)) mod m |

Where i ∈ {0, 1, ..., m-1}, h'(x), h1(x), h2(x) are auxiliary hash functions, c1, c2 are positive auxiliary constants.

Examples

Let x ∈ U = {1, ..., 1000} and h(x) = x mod m. The next table shows the hash values in case of not prime and prime. Bolded text indicates the same hash values.

x | m = 100 (not prime) | m = 101 (prime) |
–– | –– | — |
723 | 23 | 16 |
103 | 3 | 2 |
738 | 38 | 31 |
292 | 92 | 90 |
61 | 61 | 61 |
87 | 87 | 87 |
995 | 95 | 86 |
549 | 49 | 44 |
991 | 91 | 82 |
757 | 57 | 50 |
920 | 20 | 11 |
626 | 26 | 20 |
557 | 57 | 52 |
831 | 31 | 23 |
619 | 19 | 13 |

Links

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents