I implemented binary search, linear search and hash table to compare each time complexity. The problem is that somehow my hash table is much slower than binary search, when I measure the time to find prime numbers. Below is my code:
// Make the hash table 20 times the number of prime numbers HashTable::HashTable(std::vector<int> primes) { int tablesize = primes.size() * 20; table = new std::list<int>[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<int>::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
I already tried to exceed the table size to exclude collisions, but I did not notice any difference.

source share