Linear probes are another way to solve hash conflicts. The basic idea of this method is to find the next vacant space until the vacant space is found in case of a hash conflict.
Example
Insert a value S first, for example.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + fingerprint + 6gjpc9wpgo8cd4kpgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140617/20140617083849201.jpg" alt = "\">
Insert another value H. Because H conflicts with the HA System of A, you need to find an empty position.
Vacant Space found
Insert
Code
Public class LinearProbeST
{Private static final int M = 100; private Key [] keys = (Key []) new Object [M]; private Value [] values = (Value []) new Object [M]; public LinearProbeST () {} public Value get (Key key) {int hash = hash (key); for (int I = 0; I <M; I ++) {int index = (hash + I) % M; Key key2 = keys [index]; // the Key if (key2 = null) return null cannot be found; // The key if (key. equals (key2) {return values [index] ;}} return null;} public void put (Key key, Value value) {int hash = hash (key ); for (int I = 0; I <M; I ++) {int index = (hash + I) % M; Key key2 = keys [index]; // if (key2 = null) {keys [index] = key; values [index] = value; return;} is found ;} // locate the existing value if (key. equals (key2) {values [index] = value; return ;}} private int hash (Key key) {return (key. hashCode () & 0x7fffffff) % M ;}}
Performance
As the amount of data increases, the speed of conflicting hash values slows down. In the case of few conflicts, the complexity of each operation is approximately 1. In the case of many conflicts, the complexity of each operation can reach N. Therefore, M = N/2 is generally used, which has the best performance without wasting space.
Knuth parking problems
There is a fixed-size parking lot where every car stops at random position I. If the parking space I is occupied, find the parking spaces I + 1 and I + 2.
The linear probe algorithm is actually a Knuth parking problem. Http://arxiv.org/abs/math/0502220