Code implementation of "Find" hash table "Data structure and algorithm"

Source: Internet
Author: User
Tags int size random seed
Hash tables are also called hash lists, and hash storage structures are primarily lookup-oriented.
The hashing technique establishes a definite correspondence between the stored location of the record and its key words, so that each keyword key corresponds to a storage location F (key). Hash address/Storage location = f (keyword)
The construction of hash table/hash table mainly relies on solving two problems: 1, the method of constructing hash function, 2, the processing method of hash conflict.
The two principles of constructing a hash function: 1, simple calculation, 2, hash address/storage location The value of the/F () function is evenly distributed.
How to construct a hash function:
Construction method hash function Application Scenarios
Direct Addressing method F (key) = A * key +b (A, B is constant) It is appropriate to know the distribution of keywords and look for small and continuous tables.
Digital Analysis Method Extract some numbers for example: inversion, Zoo displacement, right-ring displacement, first two numbers and the last two numbers added Suitable for the knowledge of keyword distribution, and the number of key bits, the number of bits of the keyword distribution is more uniform situation.
The method of square take Number of squares to take the middle of several It is suitable for cases where the keyword distribution is not known and the number of keywords is not many.
Folding method Sum the number of strings by averaging several parts Suitable for situations where the keyword distribution is not known and the number of keywords is more.
Residual remainder method (most commonly used) F (key) = key mod p (p <= m) NA
Random number method F (key) = random (key) Suitable for cases where the length of the keyword varies.

How to handle hash conflicts:
Processing methods hash function
Open addressing Method (linear detection) Fi (key) = (f (key) + di) MOD m
DI = 1, 2, 3, ...., m-1
Open addressing Method (two-time detection) Fi (key) = (f (key) + di) MOD m di = 1^2, -1^2, 2^2, -2^2, ..., q^2,-q^2, Q<=M/2
Open addressing Method (random detection) Fi (key) = (f (key) + di) MOD m di is a pseudo-random sequence, i.e., with the same random seed, each time the resulting sequence is the same.
Re-hashing Function method Fi (key) = RHi (key) i = 1, 2, ..., K RHi is a different hash function and can be constructed using a different hash function construction method.
Chain Address method Only the pointer is stored in the hash list, and the pointer points to the synonym child table.
Public area Overflow Method Only one record is stored in the hash list, and other synonyms are stored in the public overflow area.

Hash list Lookup Performance analysis angle: 1, the hash function is uniform, 2, the method of dealing with the conflict; 3. Filling factor of the hash table: filling factor = The number of records in the list/length of the hash list. The greater the filling factor, the greater the likelihood of conflict. It is common practice to set the length of the hash table to be larger than the lookup set, to change the space time, and to improve the lookup efficiency.
FILENAME:HASH.H

#ifndef hash_h_included
#define hash_h_included

#define HASH_TABLE_SIZE  // Hash table size, modify
the typedef int HELEMTYPE According to the actual situation,//the type of elements stored in the hash table, modify #define Hash_elem_invalid_value According to the actual situation
0x7FFFFFFF Invalid element value, assumed to be the maximum positive integer
typedef struct HashTable
{
    helemtype *pelem;   hash table, array form, dynamic allocation, each element initial value is hash_elem_invalid_value
    int totalnum;       Hash table can be stored in the elements, hash table after applying fixed invariant
    int existnum;       The elements that have been stored in the hash table are initially 0, each inserting a
}hashtable;

#define HASH_ERROR_INIT         1
#define HASH_ERROR_MALLOC       2
#define Hash_error_key          3
# Define Hash_error_full         4
#define HASH_ERROR_NOT_FOUND    5

int hash_main ();

#endif//hash_h_included

Filename:hash.c #include <stdio.h> #include <stdlib.h> #include "public.h" #include "hash.h"//hash table initialization, ha

    The Greek table length is size int inithashtable (HashTable *ph, int size) {int i = 0; if ((!ph) | | |
    (size <= 0))
    {return hash_error_init;
    } Ph->pelem = malloc (sizeof (helemtype) * size);
    if (!ph->pelem) {return hash_error_malloc;
    } for (i = 0; i < size; i++) {ph->pelem[i] = Hash_elem_invalid_value;
    } ph->totalnum = size;

    Ph->existnum = 0;
return OK;

}//hash function: computes hash address int hash (int key) {return key% Hash_table_size;} Find keyword, return hash address int Searchhash (HashTable *ph, int key, int *paddr) {if ((!ph) | | (!PADDR))

    return ERROR;

    The key value cannot be the same as the initial default value of the HASH table element, otherwise it will be overridden by the following element if (Hash_elem_invalid_value = = key) return hash_error_key;
    Perform a find operation *paddr = Hash (key);
        while (PH-&GT;PELEM[*PADDR]! = key) {*paddr = (*paddr + 1)% Hash_table_size; if ((Hash_elem_invalid_value = = ph->pelem[*paddr]) | |
        (*paddr = = Hash (key)))
        {return hash_error_not_found;
}} return OK;

    }//Insert element, conflict handling method: Open addressing method linear probe int Inserthash (HashTable *ph, int key) {int addr;

    if (!PH) return ERROR;

    The key value cannot be the same as the initial default value of the HASH table element, otherwise it will be overridden by the following element if (Hash_elem_invalid_value = = key) return hash_error_key;

    The table is full and cannot be inserted, returning an error if (Ph->existnum >= ph->totalnum) return hash_error_full;
        The element that has already been inserted cannot be inserted repeatedly if (ok = = Searchhash (PH, Key, &addr)) {printf ("the element is already in the hash table without having to insert the duplicate \ n");
    return OK;
    }//insert operation addr = Hash (key);
    while (hash_elem_invalid_value! = Ph->pelem[addr]) {addr = (addr + 1)% Hash_table_size;
    } ph->pelem[addr] = key;
    ph->existnum++;
return OK;

    }//delete keyword, there is delete, no operation int Deletehash (HashTable *ph, int key) {int addr;

    if (!PH) return ERROR; The key value cannot be the same as the initial default value of the HASH table element, otherwise it will be overridden by the following element if (HASH_ELEM_INVAlid_value = = key) return hash_error_key; if (OK = = Searchhash (PH, Key, &addr)) {if (ph->existnum <= 0) ph->existnum = 1;//The exception should be indicated here that the program
        existing problems;
        PH-&GT;PELEM[ADDR] = Hash_elem_invalid_value;
    ph->existnum--;
    }//printf ("Deletehash (): element%d to be deleted was not found", key);
return OK;
    }//Print hash table void Printhash (HashTable *ph) {int i;

    if (!PH) return;
    printf ("Hash Table: Space size:%d, number of elements:%d.\n", Ph->totalnum, Ph->existnum);
    printf ("-----------------------------------\ n");
    printf ("Subscript element value \ n");

    printf ("-----------------------------------\ n");
    for (i = 0; i < ph->totalnum; i++) {printf ("%-8d%-6d\n", I, ph->pelem[i]);
    } printf ("-----------------------------------\ n");
Return
    } int Hash_main () {int input;
    int addr;
    int key;
    int RetCode;

	HashTable H;
		while (1) {printf ("----------------------------------\ n");
		printf ("hash table basic operation \ n"); printf ("----------------------------------\ n ");
		printf ("0. Create/initialize hash table \ n");
		printf ("1. Insert element \ n");
		printf ("2. Delete element \ n");
		printf ("3. Find element \ n");
		printf ("4. Print hash table \ n");
		printf ("9. Exit system \ n");
		printf ("----------------------------------\ n");
		printf ("Please select:");
		scanf ("%d", &input);

		GetChar ();
                switch (input) {Case 0:retcode = inithashtable (&h, hash_table_size);
                if (ok = = RetCode) {printf ("Create/initialize hash table succeeded!\n"); } else {printf ("Create/Initialize hash table failed!!!
                \ n ");


            } break;
                Case 1:printf ("Please enter the element to be inserted:--");
                scanf ("%d", &key);
                RetCode = Inserthash (&h, key);
                if (ok = = RetCode) {printf ("Insert element succeeded!\n"); } else {printf ("Insert element failed!!!
                \ n ");
            }    Break
                Case 2:printf ("Please enter the element to be deleted:--");
                scanf ("%d", &key);
                RetCode = Deletehash (&h, key);
                if (ok = = RetCode) {printf ("delete element succeeded!\n"); } else {printf ("delete element failed!!!
                \ n ");

            } break;
                Case 3:printf ("Please enter the element to be found:--");
                scanf ("%d", &key);
                RetCode = Searchhash (&h, Key, &AMP;ADDR);
                if (ok = = RetCode) {printf ("Find element succeeded, location is:%d.\n", addr); } else {printf ("Find element failed!!!
                \ n ");

            } break;
                Case 4:printhash (&AMP;H);

            Break Case 9:printf ("the system has exited.
                \ n ");

            Exit (0); Default:printf ("Invalid, please re-select operation.)
                \ n ");
		Exit (0);
}} return 0;
 }



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.