C语言哈希查找

用C语言现哈希查找,使用线性探测法解决冲突

设哈希表的长度为11,哈希函数为H(key)=key%11,随机产生小于50的8个数,然后存入哈希表中,查找中使用线性探测法解决冲突。

#include
#include
#include   
#define Max 11   
#define N 8
int hashtable[Max];   /* 定义哈希表的长度为11 */
int func(int value)
{
    return value%Max;    /*哈希函数,返回哈希值*/
}
int search(int key)
{
    int pos,t;
    pos=func(key);    /* 哈希函数确定的位置 */
    t=pos;             /* t存放确定出的位置 */
    while(hashtable[t]!=key && hashtable[t]!=-1)  /* 产生冲突 */
    {
        t=(t+1)%Max;   /* 利用线性探测求出下一个位置 */
        if(pos==t)
            return -1; /* 如果经多次探测又回到用哈希函数求出的位置,则说明要查找的数不存在 */
    }
    if(hashtable[t]==-1)
        return -1;
    else
        return t;
}
void createhash(int key)
{
   int pos,t;
   pos=func(key);
   t=pos;
   while (hashtable[t]!=-1) /*  说明该位置有元素存在 */
   {
        t=(t+1)%Max;
        if(pos == t)
        {
            printf("哈希表已满\n");
            return;
        }
   }
   hashtable[t] = key;
}
void main()
{
    int flag[50];  /* 定义标记变量 */
    int i,j,t;
    for(i=0;i0&&t<50)
    {
        i=search(t);
        if(i!=-1)
            printf("查找成功!其位置是:%d\n",i);
        else
            printf("查找失败!");
    }
    else
        printf("输出有误!");
}

C语言哈希查找_第1张图片 

你可能感兴趣的:(哈希算法,c语言,数据结构)