Data Structure --- Hash table in C Language)
// Hash # include
# Include
# Define OK 1 # define ERROR 0 # define TRUE 1 # define FALSE 0 # define SUCCESS 1 # define UNSUCCESS 0 # define HASHSIZE 7 # define NULLKEY-32768 typedef int Status; typedef struct {int * elem; // base address int count; // number of current data elements} HashTable; int m = 0; // hash table length/* initialization */Status Init (HashTable * hashTable) {int I; m = HASHSIZE; hashTable-> elem = (int *) malloc (m * sizeof (int); // apply for memory hashTable-> count = m; for (I = 0; I
Elem [I] = NULLKEY;} return OK;}/* Hash function (except the remainder) */int Hash (int data) {return data % m ;} /* Insert */void Insert (HashTable * hashTable, int data) {int hashAddress = Hash (data ); // obtain the hash address // a conflict occurs while (hashTable-> elem [hashAddress]! = NULLKEY) {// solve the conflict using the open-address linear probing hashAddress = (++ hashAddress) % m ;}// Insert the value hashTable-> elem [hashAddress] = data ;} /* Search */int Search (HashTable * hashTable, int data) {int hashAddress = Hash (data ); // obtain the hash address // a conflict occurs while (hashTable-> elem [hashAddress]! = Data) {// solve the conflict by using the open-address linear Probing Method hashAddress = (++ hashAddress) % m; if (hashTable-> elem [hashAddress] = NULLKEY | hashAddress = Hash (data) return-1;} // return hashAddress ;} /* print the result */void Display (HashTable * hashTable) {int I; printf (// =========================================== //); for (I = 0; I
Count; I ++) {printf (% d, hashTable-> elem [I]);} printf (// ================================================== //);} int main () {int I, j, result; HashTable hashTable; int arr [HASHSIZE] = {13, 29, 27,28, 26,30, 38 }; printf (***************** Hash algorithm ***************); // initialize the hash table Init (& hashTable); // insert data for (I = 0; I