The use and advantages of a hash table

Source: Internet
Author: User

Data structure: hash_map principle
This is a section that gives you an in-depth understanding of hash_map, if you just want to be swallowed, don't want to understand the principle, you can skip this section, but I suggest you look at it, it doesn't hurt to know more.

Hash_map is based on a hash table (hash table). The biggest advantage of hash table is that the time of storing and searching data is greatly reduced, which is almost regarded as constant time, and the cost is only more memory. However, in the current more and more available memory, it is worthwhile to use space for time. In addition, coding is also one of the characteristics of its relatively easy.

The basic principle is to use an array with a subscript range that is larger to store the elements. You can design a function (hash function, also called a hash function, so that the keywords for each element correspond to a function value (that is, an array subscript, a hash value), which is used to store the element by using the array element, or it can be simply understood to "classify" each element according to the keyword, The element is then stored in the corresponding "class" where it is called a bucket.

However, it is not possible to guarantee that the keyword of each element corresponds to a function value of one by one. So it is very likely that the same function values are computed for different elements, thus creating a "conflict", in other words, to separate elements into the same "class". In general, "direct addressing" and "conflict resolution" are two major features of a hash table.

Hash_map, first allocate a large amount of memory, forming many barrels. is to use the hash function, the key is mapped to different regions (barrels) to save. The insertion process is:

1. Get key
2. Hash value obtained by hash function
3. Get the bucket number (generally for the hash value of the bucket number of modulo)
4. Store key and value in bucket.

Its value process is:

1. Get key
2. Hash value obtained by hash function
3. Get the bucket number (generally for the hash value of the bucket number of modulo)
4. Compare whether the inner element of the barrel is equal to key, and if it is not equal, it is not found.
5. Take out the value of an equal record.

In Hash_map, the direct address is generated by hash function, which solves the conflict and solves it by comparison function. As you can see here, if there is only one element inside each bucket, then there is only one comparison for the lookup. Many queries are faster when there is no value in many barrels (when they are not found).

Thus, to achieve a hash table, and user-related is: hash function and comparison function. These two parameters are exactly the parameters we need to specify when using Hash_map.

Source: Http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailHashMap

An implementation
/**program: A comprehensive operation of a hash table **/

/**content:insert,search,deltet **/

/* * * * * * * * * * * * * * * * * * * * * * * **/

#include <math.h>

#include <stdio.h>

#include <stdlib.h>

#define MAXSIZE 30/* The maximum capacity of the hash table is related to the hash function used.

typedef enum{false,true} BOOL;

typedef Enum{nullkey,havekey,delkey} Haveornot;

/* Hash table elements of three states, no records, records, have records but have been deleted * *

typedef struct/* Defines the structure of a hash table * *

{

int elem[maxsize]; /* Data Element Body * *

Haveornot Elemflag[maxsize]; /* element status flag, no records, records, records but has been deleted * *

int count; /* The number of current elements in the hash table * *

}hashtable;

typedef struct

{int keynum;/* Record data field, only keyword one item * *

}record;

void Initialhash (hashtable*); /* Initialize HASH table * *

void CreateHash (hashtable*);/* Create a hash table based on a series of integers entered from the keyboard * *

void Printhash (HashTable); /* Display all elements in the hash table * *

BOOL Searchhash (hashtable,int,int*); /* Find element in hash table * *

BOOL Inserthash (Hashtable*,record); /* insert element in hash table * *

BOOL Deletehash (Hashtable*,record); /* Delete element in hash table * *

int Hash (int); /* Hash Function * *

void Main ()

{

HashTable H; /* Declaration Hash Table h*/

Char ch,j= ' y ';

int position;

Record R;

BOOL temp;

Textbackground (3); /* Set Screen color * *

TextColor (15);

CLRSCR ();

Initialhash (&H);

CreateHash (&H);

/*-------------------------PROCEDURE Instructions-------------------------------* *

printf ("This program would show you to operate to a hashtable./n");

printf ("You can display all Elems,search a elem,/ninsert a elem,delete a elem./n");

/*----------------------------------------------------------------*/

while (j!= ' n ')

{

printf ("1.display/n");

printf ("2.search/n");

printf ("3.insert/n");

printf ("4.delete/n");

printf ("5.exit/n");

scanf ("%c", &ch); /* Input Operation option * *

Switch (CH)

{

Case ' 1 ': if (h.count) Printhash (H); /* Hash Table not empty * *

else printf ("The HashTable has no elem!/n");

Break

Case ' 2 ': if (! H.count) printf ("The HashTable has no elem!/n"); /* Hash Table empty */

Else

{printf ("Please input the keynum (int) of the Elem to search:");

scanf ("%d", &r.keynum); * * Enter the key word of the record

Temp=searchhash (h,r.keynum,&position);

/*temp=true: Record search success; Temp=false: no Records found

if (temp) printf ("The position of the Elem is%d/n", position);

else printf ("The elem isn ' t exist!/n");

}

Break

Case ' 3 ': if (h.count==maxsize)/* Hash Table full */

{printf ("The HashTable is full!/n");

Break

}

printf ("Please input the elem (int) to insert:");

scanf ("%d", &r.keynum); /* Enter the record you want to insert * *

Temp=inserthash (&H,R);

/*temp=true: Record insert succeeded; Temp=false: Record with same keyword

if (temp) printf ("sucess to insert the elem!/n");

else printf ("Fail to insert" elem. The same elem has been exist!/n ");

Break

Case ' 4 ':p rintf ("Please input the keynum of the Elem (int) to delet:");

scanf ("%d", &r.keynum); /* Enter the keyword to delete the record * *

Temp=deletehash (&H,R);

/*temp=true: Record deletion was successful; Temp=false: The record does not exist * *

if (temp) printf ("sucess to delete the elem!/n");

else printf ("The elem isn ' t exist in the hashtable!/n");

Break

default:j= ' n ';

}

}

printf ("The program is over!/npress any key to shut off the window!/n");

GetChar ();

}

void Initialhash (HashTable *h)

{/* Hash table initialization * *

int i;

(*h). count=0;

For (i=0;i<maxsize;i++) (*h). Elemflag[i]=nullkey;

}

void CreateHash (HashTable *h)

{/* Create a hash table based on a series of integers entered from the keyboard (no more than 12, ending with-1)

Record e;

printf ("Please enter a series of integers (no more than 12, ending with-1) to create a hash table:/n");

scanf ("%d", &e.keynum);

while (E.keynum!=-1)

if (Inserthash (h,e)) scanf ("%d", &e.keynum);

Else

{printf ("Please enter the data that is not duplicated.) ");

Return

}

}

void Printhash (HashTable H)

{/* Displays all elements of the hash table and their location. *

int i;

for (i=0;i<maxsize;i++)/* Displays the location of the record in the hash table * *

if (h.elemflag[i]==havekey)/* Displays only the elements marked as Havekey (stored with records) * *

printf ("%-4d", I);

printf ("n");

for (i=0;i<maxsize;i++)/* Display the record value in the hash table * *

if (H.elemflag[i]==havekey)

printf ("%-4d", H.elem[i]);

printf ("/ncount:%d/n", H.count); /* Display hash Table current record number * *

}

BOOL Searchhash (HashTable h,int k,int *p)

{/* Find the data element with the keyword K in the Open addressable hash table H, and if the lookup succeeds, indicate by P

The position of the data element in the table and returns TRUE, otherwise the insertion position is indicated by P, and

Back to false*/

int p1;

p1= (*p) =hash (k); /* Obtain HASH address * *

while (h.elemflag[(*p)]==havekey&&k!=h.elem[(*p)))

/* The location is filled with a record and the keyword is not equal * *

{

(*p) + +; /* Conflict handling method: Linear detection and then hashing * *

if ((*p) >=maxsize) (*p) = (*p)%maxsize; * * Cyclic search/*

if ((*p) ==p1) return False; /* The entire table has been searched, not found the element of the discovery * *

}

if (k==h.elem[(*p)]&&h.elemflag[(*p)]==havekey)/* Find success, p indicates the location of the element to be found

return True;

else return False; /* Lookup not successful */

}

BOOL Inserthash (HashTable *h,record e)

{*/* insert element e into open addressable hash table H for unsuccessful lookups, and return true, otherwise return false*/

int p;

if (Searchhash (*h), e.keynum,&p))/* The element with the same keyword as E is already in the table * *

return False;

Else

{(*h). Elemflag[p]=havekey/* Set flag to Havekey, indicating that the location has been recorded.

(*h). Elem[p]=e.keynum; /* Insert Record * *

(*h). count++; * * Hash table current length plus a/*

return True;

}

}

BOOL Deletehash (HashTable *h,record e)

{/* Deletes the deleted element e when the lookup succeeds, and returns True, otherwise returns false*/

int p;

if (! Searchhash ((*h), e.keynum,&p) * * Table does not exist to delete elements * *

return False;

Else

{(*h). Elemflag[p]=delkey/* Setting flag is Delkey, indicating that the element has been deleted */

(*h). count--; /* Hash table current length minus one * *

return True;

}

}

int Hash (int kn)

{/* hash function: H (key) =key MOD 11*/

return (KN%11);

}

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.