哈斯开放地址法源码
///
//
// author: kangquan@scut2008
//
// blog: http://blog.csdn.net/kangquan2008
//
// description: process by hash method,and find the specfic data.
//
///
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_TABLE_SIZE 10
#define MODE_NUM (HASH_TABLE_SIZE-1)
#define FLAG_NULL -1
int hash_result[HASH_TABLE_SIZE];
void initial_table()
{
memset(hash_result,FLAG_NULL,sizeof(hash_result));
}
int mode_fun(int data)
{
return data % MODE_NUM;
}
int insert_table(int data)
{
int index = mode_fun(data);
if(hash_result[index] != FLAG_NULL)
while(hash_result[index = (++index) % HASH_TABLE_SIZE] != FLAG_NULL)
;
hash_result[index] = data;
return index;
}
void display()
{
for(int i=0; i<HASH_TABLE_SIZE; i++)
printf("%d ",hash_result[i]);
printf("\n");
}
int find_num(int data)
{
int index;
int tmp;
index = mode_fun(data);
tmp = index;
while(hash_result[index%HASH_TABLE_SIZE] != data)
{
index ++;
if(index%HASH_TABLE_SIZE == tmp)
break;
}
if(hash_result[index%HASH_TABLE_SIZE] == data)
return index%HASH_TABLE_SIZE;
else
return -1;
}
int main()
{
initial_table();
int data[HASH_TABLE_SIZE] = {10,23,35,43,52,360,170,890,190,55};
for(int i=0; i<HASH_TABLE_SIZE; i++)
insert_table(data[i]);
display();
while(1)
{
int target;
printf("please input the target :");
scanf("%d",&target);
if(target == -1)
break;
int rt = find_num(target);
if( rt != -1 )
printf("the index in [0...size-1] is %d\n",rt);
else
printf("%s\n","Can not find");
}
return 0;
}