Data Structure interview 13th-hash table (hash table)
Note: The interview book has related exercises, but the ideas are relatively unclear and the layout is incorrect. The author has rewritten the related books and opinions for your reference.
13. Data Structure interview 13-hash table
1. Basic Concepts
If a record with the same keyword and K exists in the structure, it must be stored at the location of F (k. Therefore, you can directly obtain the queried records without comparing them. This ing relationship F isHash Function(Hash function), according to this idea, the table isHash.
Different keywords may obtain the same hash address, that is, key1 =key2, and F (key1) = f (key2), which is calledConflict. Keywords with the same function value are called for the hash function.Synonym. To sum up,Based on the hash functionThe H (key) method maps a set of keywords to a finite continuous address set (interval, the keyword "image" in the address set is used as the storage location of the record in the Table. Such a table is called a hash table or a hash, the resulting storage location is a discrete address.
If the probability of a hash function image to any address in the address set is equal for any keyword in the keyword set, the hash function is calledUniform Hash Function(Uniform hash function), which is to make the keyword get a "random address" through the hash function, so as to reduce conflicts.
2. Common Methods for constructing Hash Functions
The hash function allows you to access a data sequence more quickly and effectively. Through the hash function, data elements are located faster.
[1]Direct addressing: The linear function value of a keyword or keyword is a hash address. That is, H (key) = key or H (key) = A • Key + B, where A and B are constants (this hash function is called its own function)
[2] digital analysis:
Generally, some larger prime numbers are used for better results.
[3] China and France: Calculate the key value and take the intermediate R bit to form a 2 ^ r bit table.
[4] Folding Method: Adds up the ASCII codes of all characters (for strings ).
[5]Random Number method:Select a random function. The random function value of the keyword is its hash address, that is, H (key) = random (key), where random is a random function. This method is usually used to construct a hash function when the length of a keyword is not equal.
[6]Except the remaining remainder: The remainder obtained after the keyword is divided by a number p that is not greater than the m value of the hash table is the hash address. That is, H (key) = Key mod P, P <= m. You can not only directly modulo keywords, but also perform the modulo operation after the folding and square calculation. The choice of P is very important. Generally, the prime number or M is used. If P is not good, synonyms are easily generated. This is the simplest and most commonly used method for constructing hash functions.
[7]Common Methods for stringFor example, elfhash and bkdrhash (easier to write and more efficient)
3. methods for handling conflicts
[1]Open addressing method;Hi = (H (key) + DI) mod m, I = 1, 2 ,..., K (k <m-1), where H (key) is the hash function, M is the length of the hash list, Di is the incremental sequence, there are three methods available:
DI = 1, 2, 3 ,..., M-1, which is called linear detection and then hashed;
DI = 1 ^ 2,-1 ^ 2, 2 ^ 2,-2 ^ 2, 2 ^ 2 ,..., ± K ^ 2, (k <= m/2) is called secondary detection and then hashed;
DI = pseudo-random number sequence, which is called pseudo-random detection and then hash.
[2] re-Hash/re-Hash:Hi = Rhi (key), I = 1, 2 ,..., K Rhi is a different hash function, that is, when the synonym generates an address conflict, calculate the address of another hash function until the conflict does not occur. This method is not easy to generate "clustering ", however, the computing time is increased.
[3] link address method (Zipper method)
[4] creating a public overflow Zone
4. Search Performance Analysis
The process of searching a hash is basically the same as that of creating a table. Some key codes can be directly found through the address converted by the hash function, and some other key codes conflict with the address obtained by the hash function, and need to be searched by the method of handling the conflict. In the three methods described to deal with conflicts, the search after a conflict still compares the given value with the key code. Therefore, the average search length is still used to measure the efficiency of hash search.
The number of key code comparisons during the search process depends on the number of conflicts generated, resulting in fewer conflicts, higher search efficiency, more conflicts, and lower search efficiency. Therefore, the factors that affect the number of conflicts, that is, the factors that affect the search efficiency. There are three factors that affect the number of conflicts:
[1] whether the hash function is even;
[2] methods for handling conflicts;
[3] fill factor of the hash table.
The fill factor of the hash table is defined as α = the number of elements in the table/the length of the hash table.
α is a factor that indicates the filling degree of the hash list. Since the table length is a fixed value, α is proportional to the number of elements in the input table. Therefore,
The larger uα, the more elements in the input table, the higher the possibility of conflict;
The smaller the uα value, the fewer elements in the input table, and the smaller the possibility of conflict.
In fact, the average search length of the hash list is the function of filling factor α, but different methods of dealing with conflicts have different functions.
5. Simple Hash Table Implementation
Template <typename _ type> class hashtable {public: hashtable (INT length) {element = new _ type [length]; for (INT I = 0; I <length; I ++) {element [I] =-1;} This-> length = length; Count = 0 ;}~ Hashtable () {Delete [] element;} // hash function virtual int Hash (_ type data) {return data % length ;} // re-hash the virtual int rehash (INT index, int count) {return (index + count) % length );} // check whether an element is in the virtual bool serachhash (_ type data, Int & Index) {Index = hash (data); int COUNT = 0; while (element [Index]! =-1 & element [Index]! = Data) {Index = rehash (index, ++ count);} return (Data = element [Index]? True: false);} virtual int serachhash (_ type data) {int Index = 0; If (serachhash (data, index) {Return Index ;} else {return-1 ;}/// insert element bool inserthash (_ type data) {int Index = 0; If (count <length &&! Serachhash (data, index) {element [Index] = data; count ++; return true;} return false;} // set the hash table length void setlength (INT length) {Delete [] element; element = new _ type [length]; for (INT I = 0; I <length; I ++) {element [I] =-1 ;} this-> length = length;} // delete an element void remove (_ type data) {int Index = serachhash (data); If (index! =-1) {element [Index] =-1; count -- ;}// delete all elements void removeall () {for (INT I = 0; I <length; I ++) {element [I] =-1;} COUNT = 0;} void print () {for (INT I = 0; I <length; I ++) {printf ("% d", element [I]);} printf ("\ n");} protected: _ type * element; // hash table int length; // hash table size int count; // current hash table size}; void main () {hashtable <int> H (10); printf ("hash length (10) test: \ n "); int array [6] = {49,38, 65,97, 13 ,49}; For (INT I = 0; I <6; I ++) {printf ("% d \ n", H. inserthash (array [I]);} H. print (); printf ("find (97): % d \ n", H. serachhash (97); printf ("find (49): % d \ n", H. serachhash (49); H. removeall (); H. setlength (30); printf ("hash length (30) test: \ n"); For (Int J = 0; j <6; j ++) {printf ("% d \ n", H. inserthash (array [J]);} H. print (); printf ("find (97): % d \ n", H. serachhash (97); printf ("find (49): % d \ n", H. serachhash (49); System ("pause ");}