Hash Algorithm for PHP core technologies and best practices

Source: Internet
Author: User
Tags spl

Hash Algorithm for PHP core technologies and best practices

Hash Algorithm for PHP core technologies and best practices

A Hash table, also known as a Hash table, maps the Key of a keyword to a location in the array to access records to speed up searching. This ing function is called a Hash function, and the array storing records is called a Hash table.

1. Hash Function

The function is to convert an input of any length into an output of a fixed length using the Hash algorithm. The output is the Hash value. This type of conversion is a compression ing, that is, the Hash value space is usually much smaller than the input space, and the input may not be hashed into the same output, it is not possible to uniquely determine the input value from the Hash value.

A good hash function must meet the following conditions: each keyword can be evenly distributed to any position in the Hash table and does not conflict with other keywords that have been hashed to the Hash table. This is the most difficult implementation of Hash functions.

2. Hash Algorithm

1) Direct remainder Method

The direct remainder method is relatively simple. You can use the keyword k divided by the size m of the Hash table to retrieve the remainder. The algorithm is as follows:

H (k) = k mod m

For example, if the size of a Hash table is m = 12 and the given keyword is k = 100, h (k) = 4. This algorithm is a remainder operation with a high speed.

2) Product Integer

Use the key word k to multiply A constant A (0

H (k) = floor (m * (kA mod 1 ))

In this example, kA mod1 indicates the fractional part of kA, and floor indicates the Integer Operation.

When the keyword is a string, the preceding Hash algorithm cannot be used. Because a string is composed of characters, you can add the ASCII codes of all characters in the string to an integer, and then calculate them according to the Hash algorithm above.

The algorithm is as follows:

Function hash ($ key, $ m ){

$ Strlen = strlen ($ key );

$ Hashval = 0;

For ($ I = 0; $ I <$ strlen; $ I ++ ){

$ Hashval + = ord ($ key {$ I });

}

Return $ hashval % $ m;

}

3) Classic Hash algorithm Times33

Unsigned int DJBHash (char * str ){

Unsignedint hash = 5381;

While (* str ){

Hash ++ (hash <5) + (* str ++ );

}

Return (hash & 0x7FFFFFFF)

}

The algorithm is constantly multiplied by 33, which is efficient and random. It is widely used in multiple open-source projects, such as Apache, Perl, and PHP.

3. Hash table

The time complexity of the Hash table is O (1), and the Hash table structure can be expressed in graphs:


To construct a Hash table, you must create an array that is large enough to store data. In addition, you need a Hash function to map the Key keyword to a location in the array.

Steps for implementing a Hash table:

1) Create an array of fixed sizes to store data.

2) design the Hash function.

3) use the Hash function to map the keywords to a certain position of the array and perform data access at this position.

4. Use PHP to implement Hash tables

Create a HashTable class with two attributes: $ buckets and $ size. $ Buckets is an array used to store data. $ size is used to record the size of the $ buckets array. Then allocate memory for the $ buckets array in the constructor. The Code is as follows:

ClassHashTable {

Private $ buckets;

Private $ size = 10;

Publicfunction _ construct (){

$ This-> buckets = new SplFixedArray ($ this-> size );

}

}

?>

In the constructor, an array of 10 is allocated to the $ buckets array. The SplFixedArray of the SPL extension is used here, instead of an ordinary array (array)

This is because the SplFixedArray array is closer to the C language array and is more efficient. When creating an array, you must provide it with an initial size.

Note: To use a SplFixedArray, you must enable the SPl extension. If it is not enabled, you can use an ordinary array instead.

Next, specify a Hash function for the Hash table. For the sake of simplicity, the simplest Hash algorithm is used here. That is, all the characters in the string are added to the remainder. The Code is as follows:

 

 

 

Public Function hashfunc ($ key ){

$ Strlen = strlen ($ key );

$ Hashval = 0;

For ($ I = 0; $ I <$ strlen; $ I ++ ){

$ Hashval + = ord ($ key {$ I });

}

Return $ hashval % $ this-> size;

}

With the Hash function, you can insert and search methods. When inserting data, use the Hash function to calculate the location of the Hash table where the keyword is located, and then save the data to this location. The Code is as follows:

Public function insert ($ key, $ val ){

$ Index = $ this-> hashfunc ($ key );

$ This-> buckets [$ index] = $ val;

}

The data query method is similar to the data insertion method. First, the Hash function is used to calculate the location of the Hash table where the keyword is located, and then the data at this location is returned. The Code is as follows:

Public function find ($ key ){

$ Index = $ this-> hashfunc ($ key );

Return $ this-> buckets [$ index];

}

So far, a simple Hash table has been written, and the Hash table will be tested below. The code list is as follows:

$ Ht = new HashTable ();

$ Ht-> insert ('key1', 'value1 ');

$ Ht-> insert ('key2', 'value2 ');

Echo $ ht-> find ('key1 ');

Echo $ ht-> find ('key2 ');

?>

Complete code: # hash. php

 

  buckets =new SplFixedArray($this->size);                    }                    PublicFunction hashfunc($key){                           $strlen= strlen($key);                           $hashval= 0;                           For($i=0;$i< $strlen;$i++){                                  $hashval+=ord($key{$i});                           }                           return$hashval % $this->size;                    }                    Publicfunction insert($key,$val){                           $index= $this -> hashfunc($key);                           $this-> buckets[$index] = $val;                    }                    Publicfunction find($key){                           $index= $this -> hashfunc($key);                           Return$this ->buckets[$index];                    }               }             $ht = newHashTable();             $ht->insert('key1','value1');             $ht->insert('key2','value2');             Echo $ht->find('key1');             Echo $ht->find('key2'); ?>


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.