The creation of a hash table

Source: Internet
Author: User
Tags define null

Establish a definite correspondence f between the storage location of the record and its keywords, so that each keyword and the unique storage location in the table corresponds, and the corresponding relationship F is a hash (hash) function, based on the idea that the table established is a hashtable.
If Key1≠key2, and F (key1) =f (Key2), this phenomenon is called conflict, and Key1 and Key2 are synonyms for the hash function f.
Depending on the Set hash function f=h (key) and the method that handles the conflict, maps a set of keywords to a limited contiguous set of addresses, where keywords are stored in the table as "elephants" in the address set, an image process called a structured hash table (hash table).
There are 5 common ways to construct a hash function:
Direct addressing method, digital analysis method, square method, excluding residue method, random number method, etc.
Note that the choice of divisor p is important when using the remainder method H (key) =key Mod P (p≤m), and it is easy to produce synonyms if p is not selected properly. In general, select P as a prime number.
There are 2 common ways in which hash functions handle conflicts:
(a) Open address law
In this method, it is subdivided into: linear probing method, square probe method, pseudorandom number sequence method, double hash function method and so on.
b) Zipper method
The Zipper method is a way to connect all the synonyms with a single chain of links. In this method, each cell in the hash table is no longer the record itself, but the head pointer of the corresponding synonym single linked list.
The average lookup length of a hash table is ASL = F (α), that is, the average lookup length of the hash table is only related to the loading factor α, and is independent of the length n of the hash table. The time complexity of a hash table is generally O (1).
For example, to design a hash table ha[0..m-1] to store n elements, the hash function uses the remainder method H (key) =key% P (p≤m) to resolve the conflict by using a linear probing method in the open addressing method.
1 design the type of hash table;
(2) Design the algorithm to find the specified keyword in the hash table;
(3) Design of the algorithm to delete the specified keyword in the hash table;
(4) Design the algorithm to insert the record of the specified key in the hash table;
5) Design a set of keywords to establish a hash table algorithm;
6 The algorithm of designing output hash table
7 Search for success, the average search length algorithm;
Solution:
Hash table ha[0..m-1]
Number of elements stored n
hash function H (key) = key% P (p≤m)
Linear probing Hi (k) = (h (k) +i) MODM, (1≤i≤m−1) h_i (k) = (H (k) +i) \, mod \,m \,, (1 \le i \le m-1)
1 The type of hash table is as follows:

#define MAXSIZE/      /define maximum hash table length
#define NULLKEY-1//define       NULL key value
#define DELKEY-2        //definition deleted keyword value
typedef int KEYTYPE;     Keyword type
typedef char *infotype;  Other data Types
typedef struct{
    KeyType key;        Key field
    InfoType data;      Other data field
    int count;          Probe number domain
}hashtable[maxsize];    Hash table Type

2 The process of locating a record of the keyword K in the hash table: calculates the hash address H (k) based on the hash function set when the table is built, if the address cell in the table is not empty (the keyword value Nullkey is represented as null) and the address keyword is not equal to K, The next address, as set at the time of the table, is found (using linear sniffing to find the next address), and so on until an address unit is empty (lookup fails, return-1), or the keyword is more equal (the lookup succeeds, the address is returned). The corresponding algorithm is as follows:

Find the keyword k
int searchht (HashTable ha,int p,keytype k) {
    int i=0,adr in the hash table;
    ADR = k%p;
    while (Ha[adr].key!=nullkey && ha[adr].key!=k)
    {
        i++;             Using linear probing method to find the next address
        ADR = (adr+1)%p;
    }
    if (ha[adr].key==k)  //Find successful return
        ADR;
    else                //lookup failed
        return-1;

}

3 The process of deleting a record of a keyword K in a hash table: Delete on a hash table that handles conflicts using open addressing, which can only be deleted by deleting the record and not actually deleting it. Set the deletion mark here as Delkey. The corresponding algorithm is as follows:

Deletes the keyword k
int deleteht (HashTable ha,int p,int k,int &n) in the hash table {
    int adr;
    ADR = SEARCHHT (HA,P,K);
    if (adr!=-1)   //Find the keyword {ha[adr].key=delkey in the hash table
        ;
        n--;       Hash table length minus 1 return
        1;
    }
    else            //The keyword return 0 was not found in the hash table
        ;

4 Insert algorithm First call lookup algorithm, if found in the table to be inserted keyword, then insert failure; If you find an open address in the table, insert the node you want to insert, which is the insert success. The corresponding algorithm is as follows:

Inserts the keyword K into the hash table
void insertht (HashTable ha,int &n,keytype k,int p) {
    int i,adr;
    ADR = k%p;
    if (Ha[adr].key==nullkey | | ha[adr].key==delkey)  //X[J] can be placed directly in the hash table
    {
        ha[adr].key=k;
        ha[adr].count=1;
    } 
    else      //When conflict occurs, the linear probing method is used to resolve the conflict
    {
        i=1;  I record X[j] The number of conflicts
        do 
        {
            ADR = (adr+1)%p;
            i++;
        } while (Ha[adr].key!=nullkey && ha[adr].key!=delkey);
        ha[adr].key=k;
        ha[adr].count=i;
    }
    n++;
}

5 The process of establishing a hash table: first, empty the keys of the nodes in the tables so that their addresses are open, and then call the Insert algorithm to insert the given sequence of keywords into the table in turn. The corresponding algorithm is as follows:

Create a hash table
void createht (HashTable ha,keytype x[],int n,int m,int p) {
    int i,n1=0;
    for (i=0;i<m;i++)  //hash table initialization
    {
        ha[i].key=nullkey;
        ha[i].count=0;
    }
    for (i=0;i<n;i++)
        insertht (ha,n1,x[i],p);
}

6 The algorithm for outputting a hash table is as follows:

Output hash table
void Dispht (HashTable ha,int n,int m) {
    float avg=0;
    int i;
    printf ("Hash table address: \ t");
    for (i=0;i<m;i++)
        printf ("%3d", I);
    printf ("\ n");
    printf ("Hash table keyword: \ t");
    for (i=0;i<m;i++)
        if (Ha[i].key==nullkey | | ha[i].key==delkey)
            printf ("   ");//output 3 spaces
        Else
            printf ("%3d", Ha[i].key);
    printf ("\ n");
    printf ("Number of searches: \ t");
    for (i=0;i<m;i++)
        if (Ha[i].key==nullkey | | ha[i].key==delkey)
            printf ("   ");//output 3 spaces
        Else
            printf ("%3d", ha[i].count);
    printf ("\ n");
    for (i=0;i<m;i++)
        if (Ha[i].key!=nullkey && ha[i].key!=delkey)
            Avg=avg+ha[i].count;
    avg=avg/n;
    printf ("Average search length asl (%d) =%.3g\n", n,avg);

}

7 to find the success of the average search length algorithm is as follows:

When looking for success, average lookup length
void Compasl (HashTable ha,int m) {
    int i;
    int s=0,n=0;
    for (i=0;i<m;i++)
        if (Ha[i].key!=delkey && ha[i].key!=nullkey)
        {
            s=s+ha[i].count;
            n++;
        }
    printf ("Find successful asl=%.3g\n", s*1.0/n);

}

The complete code is as follows:

#include <stdio.h> #define MAXSIZE 100//define maximum hash table length #define NULLKEY-1//define NULL key value #define DELKEY-2     Defines the deleted keyword value typedef int KeyType;  Keyword type typedef char *infotype;        Other data types typedef struct{KEYTYPE key;      key field InfoType data;          Other data field int count;    Probe number domain}hashtable[maxsize];
    hash table type//INSERT keyword K into the hashtable void insertht (HashTable ha,int &n,keytype k,int p) {int i,adr;
    ADR = k%p;
        if (Ha[adr].key==nullkey | | ha[adr].key==delkey)//X[J] can be placed directly in the hash table {ha[adr].key=k;
    Ha[adr].count=1;  else//When conflict occurs, use linear probing to resolve the conflict {I=1;
            I record X[j] The number of conflicts do {ADR = (adr+1)%p;
        i++;
        while (Ha[adr].key!=nullkey && ha[adr].key!=delkey);
        Ha[adr].key=k;
    ha[adr].count=i;
} n++;
    }//create hash table void Createht (HashTable ha,keytype x[],int n,int m,int p) {int i,n1=0; for (i=0;i<m;i++)//hash table initialization {HA[I].KEY=NULLKEY;
    ha[i].count=0;
for (i=0;i<n;i++) insertht (ha,n1,x[i],p);
    ///Find the keyword K int searchht (HashTable ha,int p,keytype k) {int i=0,adr in the hash table;
    ADR = k%p;             while (Ha[adr].key!=nullkey && ha[adr].key!=k) {i++;
    Using linear probing method to find the next address ADR = (adr+1)%p;
    if (ha[adr].key==k)//Find successful return ADR;

else//find failed return-1;
    }//delete the hash table keyword K int deleteht (HashTable ha,int p,int k,int &n) {int ADR;
    ADR = SEARCHHT (HA,P,K);
        if (adr!=-1)//Find the keyword {ha[adr].key=delkey in the hash table;       n--;
    Hash table length minus 1 return 1;

else//The keyword return 0 was not found in the hash table;
    }//output hash table void Dispht (HashTable ha,int n,int m) {float avg=0;
    int i;
    printf ("Hash table address: \ t");
    for (i=0;i<m;i++) printf ("%3d", I);
    printf ("\ n");
    printf ("Hash table keyword: \ t"); for (i=0;i<m;i++) if (Ha[i].key==nullkey | | ha[i].key==delkey) printf ("");
    Output 3 spaces Else printf ("%3d", Ha[i].key);
    printf ("\ n");
    printf ("Number of searches: \ t"); for (i=0;i<m;i++) if (Ha[i].key==nullkey | | ha[i].key==delkey) printf ("");
    Output 3 spaces Else printf ("%3d", Ha[i].count);
    printf ("\ n");
    for (i=0;i<m;i++) if (Ha[i].key!=nullkey && ha[i].key!=delkey) Avg=avg+ha[i].count;
    avg=avg/n;

printf ("Average search length asl (%d) =%.3g\n", n,avg);
    ///Find success, average lookup length void Compasl (HashTable ha,int m) {int i;
    int s=0,n=0;
            for (i=0;i<m;i++) if (Ha[i].key!=delkey && ha[i].key!=nullkey) {s=s+ha[i].count;
        n++;

printf ("Find successful asl=%.3g\n", s*1.0/n);
    } void Main () {int x[]={16,74,60,43,54,90,46,31,29,88,77};
    int n=11,m=13,p=13,i,k=29;
    HashTable ha;
    Createht (HA,X,N,M,P);
    printf ("\ n");D Ispht (ha,n,m);
    I=SEARCHHT (HA,P,K);
    if (i!=-1) printf ("ha[%d].key=%d\n", i,k);
  Else      printf ("%d\n not Found", K);
    k=77;
    printf ("Delete keyword%d\n", k);
    Deleteht (Ha,p,k,n);
    DISPHT (HA,N,M);
    I=SEARCHHT (HA,P,K);
    if (i!=-1) printf ("ha[%d].key=%d\n", i,k);
    else printf ("%d\n not Found", K);
    printf ("Insert keyword%d\n", k);
    INSERTHT (HA,N,K,P);
    DISPHT (HA,N,M);
printf ("\ n"); }

The effect is as follows:

Figure (1) The hash function is selected as H (key) = key% 13

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.