首页 > 代码库 > hash查找

hash查找

#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std; #define HASHSIZE 7#define NULLKEY -32768 struct HashTable{	int *elem;	int count;};void init(HashTable* hashTable){	hashTable->elem = (int*)malloc(HASHSIZE * sizeof(int));	hashTable->count = HASHSIZE; 	for(int i = 0; i < HASHSIZE; i++)		hashTable->elem[i] = NULLKEY; } int hash(int num){	return num % HASHSIZE; } void insert(HashTable* hashTable, int data){	int hash_address = hash(data); 	while(hashTable->elem[hash_address] != NULLKEY)	{		hash_address = (++hash_address)% HASHSIZE; 	}	hashTable->elem[hash_address] = data; }int search(HashTable* hashTable, int data){	int hash_address = hash(data);	while(hashTable->elem[hash_address] != data) 	{		hash_address = (++hash_address)% HASHSIZE; 		if(hashTable->elem[hash_address] == NULLKEY || hash_address == hash(data)) return -1; 	}	return hash_address;}void display(HashTable* hashTable) {	for(int i = 0; i < hashTable->count; i++)		std::cout<<hashTable->elem[i]<<std::endl; }int main(){	HashTable hashTable; 	int a[HASHSIZE] = {13,29,27,28,26,30,38}; 	init(&hashTable);	for(int i = 0; i< HASHSIZE; i++)	{		insert(&hashTable, a[i]); 	}	display(&hashTable); 	int result = search(&hashTable, 29); 	std::cout<<result<<std::endl;	return 0; }

 

hash查找