如何计算哈希表中的冲突数?

时间:2011-12-05 02:06:49

标签: c++ hash collision-detection

我的插入功能已经正确处理了碰撞,但我希望能够计算每种不同散列方式(链接,线性探测和二次探测)中的碰撞次数。我该怎么做呢?

到目前为止我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <ctime>
#include "Chaining.h"
#include "QuadraticProbing.h"
#include "LinearProbing.h"

using namespace std;

int main()
{
    int collision_count = 0;
    float diff = 0.0;
    clock_t tStart, tStop;
    string ITEM_NOT_FOUND = "ITEM_NOT_FOUND";
    std::vector<std::string> DataArray;
    std::copy(std::istream_iterator<std::string>(std::ifstream("OHenry.txt")),istream_iterator<string>(),back_inserter(DataArray));
    std::vector<std::string> QueryArray;
    std::copy(std::istream_iterator<std::string>(std::ifstream("queries.txt")),istream_iterator<string>(),back_inserter(QueryArray));

    cout << "Testing chaining probing...\n";
    HashTable_chaining ChainingHT( ITEM_NOT_FOUND, 101 );
    int i = 0;
    double average_c = 0.0;
    double total_c = 0.0;
    double temp_c = 0.0;
    while(i != DataArray.size())
    {
        tStart = clock();
        ChainingHT.insert(DataArray[i]);
        tStop = clock();
        total_c = tStop - tStart;
        temp_c = total_c + temp_c;
        average_c = total_c / DataArray.size(); 
        if(DataArray[i] != DataArray[NULL])
        {
            collision_count++;
        }
        i++;
    }   

    cout<<"The number of collisions using Chaining is: "<<collision_count<<endl;
    cout<<"The average time per insertion using Chaining is: "<<average_c<<endl;
    system("pause");
    // Quadratic Probing 
    cout << "Testing quadratic probing...\n";
    HashTable_chaining QuadraticProbingHT( ITEM_NOT_FOUND, 101 );   
    int j = 0;
    int collision_count_quadratic = 0;
    double average_qp = 0;
    while(j != DataArray.size())
    {
        clock_t tStartq = clock();
        QuadraticProbingHT.insert(DataArray[j]);
        if(DataArray[j] != DataArray[NULL])
        {
            collision_count_quadratic++;
        }
        j++;
        average_qp = (((double)(clock() - tStartq)/CLOCKS_PER_SEC) + average_qp) / DataArray.size();

    }   
    cout<<"The number of collisions using Quadratic is: "<<collision_count<<endl;
    cout<<"The average time per insertion using Quadratic is: "<<average_qp<<endl;

1 个答案:

答案 0 :(得分:6)

哈希表本身可以报告它所看到的分离数量,而不会暴露其内部实现。

对于使用探测(任何类型)的哈希表,colissions的数量等于位于与其哈希码不一致的索引处的元素的数量(这是因为它们通常已存储的位置已经是被占据)。

对于使用链接的哈希表,colissions的数量等于哈希表中的项目数减去占用的桶数(换句话说,计算除每个桶中第一个之外的所有插入项)。这也很直观。

所以我要做的就是给每个散列表一个count_colissions()方法,用相应的方法计算O(n)时间内的colissions数量并返回它。