哈希探查的三种方法

来源:互联网 发布:淘宝鸿星尔克 编辑:程序博客网 时间:2024/05/22 00:17
#include <stdio.h>#include <string.h>#include <iostream>#include <vector>using namespace std;const int MAXSIZE = 100;int hash[MAXSIZE];int MOD = MAXSIZE - 1; //小于MAXSIZE的一个质数vector<int> hashTable[MAXSIZE];/* 线性探查int LinearProbing(int num){    int p = num % MOD;    if (p < 0) //这一步是必须的,不然有可能会出现访问数组下标为负数    {        p += MOD;    }    int cnt = 0;    while (hash[p] != -1 && hash[p] != num) //如果这个位置,已经被占了,并且不是这个num    {        cnt++;        p = (p + 1) % MOD;        if (cnt == MAXSIZE)        {            return -1;        }    }    return p;}二次探查int QuadraticProbing(int num){    int p = num % MOD;    if (p < 0)    {        p += MOD;    }    int cnt = 1;    while (hash[p] != -1 && hash[p] != num)    {        cnt++;        p = (p + cnt * cnt) % MOD;        if (cnt > MAXSIZE)        {            return -1;        }    }    return p;}*/int HashFind(int num){    int p = num % MOD;    if (p < 0)    {        p += MOD;    }    return p;}int main(){    for (int i = 0; i < MAXSIZE; i++)    {        hashTable[i].clear();    }    int num;    int p;    while (cin >> num)    {        p = HashFind(num);        hashTable[p].push_back(num);        if (num == -1)        {            break;        }    }    for (int i = 0; i < MAXSIZE; i++)    {        p = HashFind(i + 1);        for (vector<int>:: iterator it = hashTable[p].begin(); it != hashTable[p].end(); ++it)        {            if (*it == i + 1)            {                cout << "find it" << endl;                break;            }        }    }    memset(hash, -1, sizeof(hash));    return 0;}

0 0
原创粉丝点击