首页 > 编程语言 > 详细

使用再哈希算法查找元素

时间:2016-01-07 10:03:00      阅读:285      评论:0      收藏:0      [点我收藏+]

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

/* 
 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# 


使用再哈希算法查找元素

原文:http://www.cnblogs.com/mengfanrong/p/5108658.html

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