Using hash tables for data lookup

Source: Internet
Author: User

Title: Now there is a hash table for storing integers, the memory unit of the hash table is called a bucket, each bucket can put 3 integers, when a bucket to put more than 3 elements, the new elements will be stored in the overflow bucket, each overflow bucket can also put 3 elements, multiple overflow bucket use linked list. The number of buckets for this hash table is the hash function of Prime P,hash table for P modulus. #include <iostream>using namespace std; #define P 7#define null_data-1#define bucket_node_size 3struct Bucket_node {int data[bucket_node_size];struct bucket_node *next;}; Bucket_node hash_table[p];void inithashtable (Bucket_node (*HT) [P]) {for (Int. i=0; i<p; ++i) {for (int j=0; j<bucket_ Node_size; ++J) {(*HT) [i].data[j] = null_data;} (*HT) [I].next = NULL;}} int Hash (int x) {return X% P;} void Insert_new_element (Bucket_node (*HT) [P], int x) {int index = Hash (x); for (int i = 0; i < bucket_node_size; i++) {if ( (*HT) [Index].data[i] = = Null_data) {(*HT) [index].data[i] = X;return;}} Bucket_node *s = new Bucket_node;s = (*HT) [Index].next;bucket_node *p = & (*HT) [Index];while (s! = NULL) {for (int i = 0; i < bucket_node_size; i++) {if (s->data[i] = = Null_data) {S->data[i] = x;//(*HT) [index] = *s;return;}} p = S;s = s->next; }s=new bucket_node;p->next=s;for (int j = 0; j<bucket_node_size; ++j) {s->data[j] = Null_data;} S->next = null;for (int i = 0; i < bucket_node_size;i++) if (s->data[i] = = Null_data) {S->data[i] = X;return;}} void Main () {inithashtable (&hash_table); int ar[] = {8,15,22,29,36,43,50,7,14,21,28,35,42,49,56,63,70,25,30};for (int i=0; i<sizeof (AR)/sizeof (int); ++i) {insert_new_element (&hash_table,ar[i]);}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Using hash tables for data lookup

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.