码迷,mamicode.com
首页 > 编程语言 > 详细

使用再哈希算法查找元素

时间:2014-12-23 22:41:24      阅读:414      评论: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://blog.csdn.net/xiangpingli/article/details/42110777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!