The hash algorithm functions as quickly as possible to find a value in the data structure. If the data is large, but there is a need to traverse the entire data structure to find the value, it takes too much time. Therefore, the hash table in the search aspect of the comparative advantage: using the hash function, you know the exact location, can be quickly retrieved. Function of the hash function: Given a key value, returns the address of the key value in the table.
1 functionHashTable () {2 //Initialize Hash table3 vartable=[];4 //hash function (Private method)5 varLoselosehashcode =function(key) {6 varHash=0;7 for(vari=0;i<key.length;i++){8Hash + =key.charcodeat (i);9 }Ten //because the added hash value is very large, in order to get a smaller value, the hash value and any number of the remainder One returnHash%37; A }; - - //The most community-recommended hash function the var Djb2hashcode=function(key) { - //Initialize the hash variable and assign it to a prime number, most of which use 5381 - //multiplies the hash by 33 (magic number) - varhash=5381; + for(vari=0;i<key.length;i++){ -hash=hash*33+key.charcodeat (i); + } A //Add the hash value of the last prime number division to take the remainder, the prime number to force the hash table size is larger. at returnhash%1013; - }; - //put the value into the hash table - This. put =function(key,value) { - varposition=Loselosehashcode (key); - //Console.log dispensable inConsole.log (position+ "-" +key); -table[position]=value; to }; + //Get - This. get =function(key) { the returnTable[loselosehashcode (key)]; * }; $ //removed fromPanax Notoginseng This. remove=function(key) { -Table[loselosehashcode (Key)]=undefined; the } +}
One of the obvious drawbacks of the Hashtable function above is that overrides occur if the different keys are inserted but the ASCII values are the same. The value that is stored later overrides the value previously deposited. To resolve conflicts, you can use separate links, linear probing, and double hashing.
Detach the link method to create a linked list at each location in the hash table and store the elements inside. Simply put, in each location, create a linked list and store different key values at once. This method adds additional storage space because of the linked list.
Linear probing method. Suppose you want to put a new element in the [320] position. If the [320] position is empty, no element is stored, it is placed directly, if an element occupies that position, the [320+1] position is tried, that is, the next position, if [320+1] is occupied, then the position of [320+1+1] is attempted, the next position is attempted, and so on, Until a vacancy is found.
JavaScript data Structures--Simple hash Table implementation