-
Notifications
You must be signed in to change notification settings - Fork 364
/
cuckoo_hashing.c
98 lines (77 loc) · 2.02 KB
/
cuckoo_hashing.c
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 <stdio.h>
#include <stdbool.h>
#define TABLE_SIZE 10
#define MAX_KICK_COUNT 5
typedef struct {
int key;
bool occupied;
} Entry;
Entry table[TABLE_SIZE];
int hash(int key) {
return key % TABLE_SIZE;
}
bool insert(int key) {
int index1 = hash(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 = hash(kickedKey);
} else {
index2 = hash(kickedKey);
}
table[kickIndex].key = key;
key = kickedKey;
}
return false;
}
bool search(int key) {
int index1 = hash(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() {
// Initialize the table
for (int i = 0; i < TABLE_SIZE; i++) {
table[i].occupied = false;
}
// Get the number of keys to insert
int numKeys;
printf("Enter the number of keys to insert: ");
scanf("%d", &numKeys);
// Insert the keys
for (int i = 0; i < numKeys; i++) {
int key;
printf("Enter key %d: ", i + 1);
scanf("%d", &key);
insert(key);
}
// Get the key to search
int keyToSearch;
printf("Enter the key to search: ");
scanf("%d", &keyToSearch);
// Search for the key
if (search(keyToSearch)) {
printf("Key %d is present\n", keyToSearch);
} else {
printf("Key %d is not present\n", keyToSearch);
}
return 0;
}