Using a linear probe method ( Linear probin is unused G ) can resolve the conflict in the hash, the basic idea is: a hash function set H (Key) = D , and assuming the hash memory structure is a circular array , then when conflict occurs when , continue probing d + 1, d + 2 , ... , until the conflict is resolved .
For example , an existing key set is {47 , 7 , 29 , 11 , 16 , 92 , 22 , 8 , 3} , is provided for the hash table entry length m = 11 , the hash function Hash (key) = key mod 11 , linear conflict detection method.
Build a hash table is as follows:
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
22 |
47 |
92 |
16 |
3 |
7 |
29 |
8 |
Now given hash function to the Hash (Key) Key = MOD m , according to the above rules required , the use of the linear probe method conflict . Required to establish the corresponding hash table, as required for printing.
Only one test case , the first one acts integers n and m ( 1 <= n, m <= 10 , 000 ), n the representative key of the total number , m represents the length of the hash table , and the hash function is to make the Hash (key ) Key = MOD m .
Next n lines, each line an integer representing a key , wherein K EY and key pairwise identical ( 0 <= key <= 10,000 ) .
Output establish good hash table, such as the following table :
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
22 |
47 |
92 |
16 |
3 |
7 |
29 |
8 |
Output should
0#11
1#22
2#NULL
3#47
4#92
5#16
6#3
7#7
8#29
9#8
10#NULL
3 5 1 5 6
0#5 1#1 2#6 3#NULL 4 # NULL
directly on the code:
1 #include <iostream> 2 using namespace std; 3 4 int hash(int key, int len) { 5 return (key % len); 6 } 7 8 int hashTable[10000]; 9 10 void initializeHash(int size, int lenOfHash) { 11 int temp; 12 13 for (int i = 0; i < size; i++) { 14 cin >> temp; 15 16 if (hashTable[hash(temp, lenOfHash)] == -1) { 17 hashTable[hash(temp, lenOfHash)] = temp; 18 } else { 19 int pos = hash(temp, lenOfHash); 20 while (hashTable[pos] != -1) { 21 pos = (pos + 1) % lenOfHash; 22 } 23 24 hashTable[pos] = temp; 25 } 26 } 27 } 28 29 void print(int lenOfHash) { 30 for (int i = 0; i < lenOfHash; i++) { 31 if (hashTable[i] != -1) { 32 cout << i << "#" << hashTable[i] << endl; 33 } else { 34 cout << i << "#NULL" << endl; 35 } 36 } 37 } 38 39 int main() 40 { 41 int numOfKey, lenOfHash; 42 43 cin >> numOfKey; 44 cin >> lenOfHash; 45 46 for (int i = 0; i < lenOfHash; i++) { 47 hashTable[i] = -1; 48 } 49 50 initializeHash(numOfKey, lenOfHash); 51 52 print(lenOfHash); 53 54 return 0; 55 }
Reproduced in: https: //www.cnblogs.com/IT-nerd/p/3462370.html