当前位置:网站首页>Hash table and full comments

Hash table and full comments

2022-07-07 02:36:00 @Landscape post yuan

 

	#include "stdio.h"
	#include "stdlib.h"
	
	typedef struct{
	    int* elem;  // Data element storage base address , Assign arrays dynamically 
	    int count;  // Number of current data elements 
	}HashTable;
	
	int m=0;        // Hash table length , Global variables 
	
	
	                //HASHSIZE  Define the hash table length as the length of the array 
	typedef enum {  // Or not typedef, take Status On the front , The function called is preceded by enum
	    OK=1,SUCCESS=1,UNSUCCESS=0,HASHSIZE=12,NULLKEY=-32768
	}Status;
	
	
	Status InitHashTable(HashTable *H){ // Initialize hash table 
	    int i;
	    m=HASHSIZE;
	    H->count=m;
	    H->elem=(int *)malloc(m*sizeof(int));
	    for(i=0;i<m;i++)
	        H->elem[i]=NULLKEY;
	    return OK;
	}
	
	
	int Hash(int key){  // Hash function   key amount to qq account number 
	    return key%m;   // Division and remainder   Return key 
	}
	
	void InsertHash(HashTable* H,int key){ // Insert keywords into hash table 
	    int addr=Hash(key);                // Find the hash address 
	    printf("The subscript of the inserted array position:%d\n",addr);
	    while(H->elem[addr]!=NULLKEY)      // If it's not empty , Then conflict 
	        addr=(addr+1)%m;               // Develop linear detection of addressing 
	    H->elem[addr]=key;                 // Until there is a space to insert keywords 
	}
	
	Status SearchHash(HashTable H,int key,int* addr){ // Insert keywords into hash table 
	    *addr=Hash(key);                              // Find the hash address 
	    while(H.elem[*addr]!=key){                    // If it's not empty , Then conflict 
	        *addr=(*addr+1)%m;                        // Develop linear detection of addressing 
	        if(H.elem[*addr]==NULLKEY||*addr==Hash(key)){
	            // If the loop goes back to the origin 
	            // Key does not exist 
	            return UNSUCCESS;
	        }
	    }
	    return SUCCESS;
	}
	
	
	int main(){
	    int i=0;
	    HashTable H;
	    InitHashTable(&H);
	    while(i<HASHSIZE){
	        InsertHash(&H,i);     // Insert 12 Number 
	        i++;
	    }
	    int key=0;
	    int addr;                // Return the function of subscript 
	    while(key<HASHSIZE){
        if(SearchHash(H,key,&addr)==SUCCESS){  // Search the position of this number 
	            printf("Print the position of this number:%d\n",addr);
	        } else{
	            printf("UNSUCCESS\n");
	        }
	        key++;
	    }
	}

原网站

版权声明
本文为[@Landscape post yuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061900073474.html