我已经实现了二进制搜索,线性搜索和哈希表来比较每个时间复杂度.问题是,当我测量查找素数的时间时,我的哈希表比二进制搜索慢得多.以下是我的代码:
// Make the hash table 20 times the number of prime numbers HashTable::HashTable(std::vectorprimes) { int tablesize = primes.size() * 20; table = new std::list [tablesize]; size = tablesize; for (auto &prime : primes) this->insert(prime); } // Hash function int HashTable::hash(int key) { return key % size; } // Finds element int HashTable::find(int key) { // Get index from hash int index = hash(key); // Find element std::list ::iterator foundelement = std::find(table[index].begin(), table[index].end(), key); // If element has been found return index // If not, return -1 if (foundelement != table[index].end()) return index; else return -1; } // Adds element to hashtable void HashTable::insert(int element) { // Get index from hash and insert the element int index = hash(element); table[index].push_back(element); }
HashTable.h
#ifndef HASHTABLE_H #define HASHTABLE_H #include#include
#include class HashTable { private: // Each position in Hashtable has an array of lists to store elements in case of collision std::list * table; // Size of hashtable int size; // Hashfunction that returns the array location for the given key int hash(int key); public: HashTable(int tablesize); HashTable(std::vector primes); // Adds element to hashtable void insert(int element); // Deletes an element by key void remove(int key); // Returns an element from hashtable for a given key int find(int key); // Displays the hashtable void printTable(); // Display histogram to illustrate elements distribution void printHistogram(); // Returns the number of lists in hash table int getSize(); // Returns the total number of elements in hash table int getNumberOfItems(); // De-allocates all memory used for the Hash Table. ~HashTable(); }; #endif
我已经尝试超过表格大小以消除碰撞,但我没有注意到任何差异.