-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashing.cpp
More file actions
67 lines (55 loc) · 1.43 KB
/
Hashing.cpp
File metadata and controls
67 lines (55 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
using namespace std;
const int TABLE_SIZE = 10;
class HashTable {
private:
int table[TABLE_SIZE];
int collisionCount[TABLE_SIZE]; // Counter to keep track of collisions
public:
HashTable() {
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = -1;
collisionCount[i] = 0;
}
}
int hashFunction(int key) {
return key % TABLE_SIZE;
}
void insert(int key) {
int index = hashFunction(key);
int probes = 1;
while (table[index] != -1) {
index = (index + 1) % TABLE_SIZE; // Linear probing without replacement
probes++;
}
table[index] = key;
collisionCount[index] = probes;
}
void display() {
cout << "Hash Table:" << endl;
for (int i = 0; i < TABLE_SIZE; i++) {
cout << "[" << i << "]: ";
if (table[i] != -1)
cout << table[i] << " (Probe: " << collisionCount[i] << ")";
else
cout << -1;
cout << endl;
}
}
};
int main() {
HashTable ht;
// Input keys into the hash table
int numKeys;
cout << "Enter the number of keys: ";
cin >> numKeys;
cout << "Enter the keys: ";
for (int i = 0; i < numKeys; i++) {
int key;
cin >> key;
ht.insert(key);
}
// Display the hash table
ht.display();
return 0;
}