使用再哈希算法查找元素

使用再哈希算法查找元素:

/* 
 hash search, using rehash method
 if find k, return 
 if not find, d=(d+step)%m, rehash find 
*/
int SearchHash(HashTable H, KeyType k)
{
        int d, d1, m;

        m = H.tableSize;
        d = d1 = k%m;

        while(H.data[d].key != -1)
        {
                if(H.data[d].key == k) //hunt 
                        return d;
                else
                        d = (d+1)%m;

                if(d==d1)
                                return -1; //fail
        }

        return -1;
}

int main(int argc, char *argv[])
{
        int hash[] = {23, 35, 12, 56, 123, 39, 342, 90};
        int m=11, p=11, n=8, pos;
        int key, index;
        HashTable H;

        CreateHash(&H, m, p, hash, n);

        key = 123;

        index = SearchHash(H, key);
        if(index < 0)
        {
                printf("find failed!\n");
                return -1;
        }

        printf("key:%d, index:%d\n", key, index);

        return 0;
}

输出结果:

root@ubuntu:/mnt/shared/appbox/hash# ./hash
[line:59] addr:1, i=0, key=23
[line:59] addr:2, i=1, key=35
[line:70] di:3, i=2, key=12
[line:70] di:4, i=3, key=56
[line:70] di:5, i=4, key=123
[line:59] addr:6, i=5, key=39
[line:70] di:7, i=6, key=342
[line:70] di:8, i=7, key=90
hash index:     0    1    2    3    4    5    6    7    8    9    10   
key value:      -1   23   35   12   56   123  39   342  90   -1   -1   
hash times:     0    1    1    3    4    4    1    7    7    0    0    
key:123, index:5
root@ubuntu:/mnt/shared/appbox/hash# 


转载于:https://www.cnblogs.com/mengfanrong/p/5108658.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值