首页 > 其他 > 详细

hash查找

时间:2014-11-05 23:01:33      阅读:411      评论:0      收藏:0      [点我收藏+]
#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查找

原文:http://www.cnblogs.com/kangbry/p/4077441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!