-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashTableRobinHood.cpp
135 lines (111 loc) · 2.41 KB
/
hashTableRobinHood.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include "hashTableRobinHood.h"
void HashTableRobinHood::rehash(size_t newCapacity)
{
int* oldTable = table;
int oldCapacity = capacity;
size = 0;
capacity = newCapacity;
table = new int[capacity];
for (int i = 0; i < capacity; i++) {
table[i] = -1;
}
for (int i = 0; i < oldCapacity; i++) {
if (oldTable[i] != -1) {
insert(i, oldTable[i]);
}
}
delete[] oldTable;
}
HashTableRobinHood::HashTableRobinHood(size_t capacity)
{
this->capacity = capacity;
size = 0;
table = new int[capacity];
for (int i = 0; i < capacity; i++) {
table[i] = -1;
}
}
HashTableRobinHood::~HashTableRobinHood()
{
delete[] table;
capacity = 0;
size = 0;
}
int HashTableRobinHood::hash(int key)
{
return key % capacity;
}
int HashTableRobinHood::hash2(int key)
{
return 1 + (key % (capacity - 1));
}
int HashTableRobinHood::probeDistance(int index)
{
return (index - hash(index) + capacity) % capacity;
}
void HashTableRobinHood::insert(int key, int value) {
int index = hash(key);
int distance = 0;
for(int i = 0; i < 10; i++) {
if (table[index] == -1) {
table[index] = value;
size++;
return;
}
// Scatter - minimaize the distance frome the ideal position
int currentDistance = probeDistance(index);
if (currentDistance < distance) {
std::swap(table[index], value);
distance = currentDistance;
}
index = (index + hash2(key)) % capacity;
distance++;
}
rehash(capacity * 2);
insert(key, value);
}
int HashTableRobinHood::search(int key) {
int index = hash(key);
int distance = 0;
for(int i = 0; i < 10; i++) {
if (table[index] != -1) {
return table[index];
}
int currentDistance = probeDistance(index);
if (currentDistance < distance) {
return -1;
}
index = (index + hash2(key)) % capacity;
distance++;
}
return -1;
}
void HashTableRobinHood::remove(int key) {
int index = hash(key);
int distance = 0;
for(int i = 0; i < 10; i++) {
if (table[index] != -1) {
table[index] = -1;
size--;
return;
}
int currentDistance = probeDistance(index);
if (currentDistance < distance) {
return;
}
index = (index + hash2(key)) % capacity;
distance++;
}
if (size < capacity / 4) {
rehash(capacity / 2);
}
}
void HashTableRobinHood::display() {
for (size_t i = 0; i < capacity; i++) {
cout << i << ": ";
if (table[i] != -1) {
cout << i << " " << table[i];
}
cout << endl;
}
}