-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathcuckoo_hashing.cpp
98 lines (77 loc) · 2.02 KB
/
cuckoo_hashing.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <vector>
using namespace std;
const int TABLE_SIZE = 10;
const int MAX_KICK_COUNT = 5;
struct Entry {
int key;
bool occupied;
Entry() {
occupied = false;
}
};
vector<Entry> table(TABLE_SIZE);
int hashFunc(int key) {
return key % TABLE_SIZE;
}
bool insert(int key) {
int index1 = hashFunc(key);
int index2 = (index1 + 1) % TABLE_SIZE;
for (int i = 0; i < MAX_KICK_COUNT; i++) {
if (!table[index1].occupied) {
table[index1].key = key;
table[index1].occupied = true;
return true;
}
if (!table[index2].occupied) {
table[index2].key = key;
table[index2].occupied = true;
return true;
}
int kickIndex = (i % 2 == 0) ? index1 : index2;
int kickedKey = table[kickIndex].key;
if (kickIndex == index1) {
index1 = hashFunc(kickedKey);
} else {
index2 = hashFunc(kickedKey);
}
table[kickIndex].key = key;
key = kickedKey;
}
return false;
}
bool search(int key) {
int index1 = hashFunc(key);
int index2 = (index1 + 1) % TABLE_SIZE;
if (table[index1].occupied && table[index1].key == key) {
return true;
}
if (table[index2].occupied && table[index2].key == key) {
return true;
}
return false;
}
int main() {
// Get the number of keys to insert
int numKeys;
cout << "Enter the number of keys to insert: ";
cin >> numKeys;
// Insert the keys
for (int i = 0; i < numKeys; i++) {
int key;
cout << "Enter key " << (i + 1) << ": ";
cin >> key;
insert(key);
}
// Get the key to search
int keyToSearch;
cout << "Enter the key to search: ";
cin >> keyToSearch;
// Search for the key
if (search(keyToSearch)) {
cout << "Key " << keyToSearch << " is present" << endl;
} else {
cout << "Key " << keyToSearch << " is not present" << endl;
}
return 0;
}