1. Hash list (hash)
The nature of the lookup: where the object is known to find.
Ordered objects: full-order, half-order
Direct "figure out" object location: Hash
Time complexity is almost constant: O (1), that is, the lookup time is independent of the problem size
The two basic tasks of the hash lookup method are:
Calculate location: Constructs the hash function to determine the keyword storage location;
Resolve conflict: Apply a strategy to solve the same problem with multiple keyword locations
The basic idea of hashing (Hashing) is:
① the keyword key as an argument, and a deterministic function H (hash function), calculates the corresponding function value, h (key), as the storage address of the data object.
② may have different keywords mapped to the same hash address, i.e. h (keyi) = h (keyj) (when Keyi≠keyj), called "Conflict (collision)".
----need some sort of conflict resolution strategy
2. How to construct a hash function
hash function two key:
① calculation is simple, in order to improve the conversion speed;
② keywords correspond to the address space distribution evenly, in order to minimize conflict.
hash function Construction of numeric keywords
① Direct Addressing method
The value of a linear function that takes a keyword is a hash address, which is
H (key) = A * key + B (A, B is constant)
② Residue Remainder method
hash function: H (key) = key mod p (general p prime number)
③ Digital Analysis method
Analyze the changes of the numeric keywords in each of you, take a more random bit as the hash address
Eg: Take the 11-digit mobile number key after the 4-bit as the address:
hash function: H (key) = Atoi (key+7) (char *key)
④ Folding Method
Divide the keywords into parts of the same number of digits, then overlay
eg:56793542
542
793
+ 056
———
1391
H (56793542) = 391
⑤ the method of square take
eg:56793542
56793542
X 56793542
—————————
3225506412905764
H (56793542) = 641
hash function Construction of character keywords
① a simple hash function--ascii code addition and method
For the character keyword key, define the hash function as follows:
H (key) = (Σkey[i]) mod tablesize
② Simple Improvement-the first 3 character shift methods (easy to create space waste)
H (key) = (key[0]*27^2 + key[1]*27 + key[2]) mod tablesize
③ Good hash function--shift method
It involves all n characters of the keyword and is well distributed:
Eg:h ("abcde") = ' a ' *324+ ' B ' *323+ ' C ' *322+ ' d ' *32+ ' e '
Index Hash (const char *key, int tablesize)
{
unsigned int h = 0; /* Hash function value, initialized to 0 */
while (*key! = ') */* Displacement map */
h = (h << 5) + *key++;
return h% Tablesize;
}
......
Data structure Learning Note 07 Hash lookup