-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hashtable.cpp
executable file
·96 lines (85 loc) · 2.37 KB
/
Hashtable.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
static int PRIME_ONE = 5;
static int PRIME_TWO = 7;
typedef struct {
string key,
int value;
} Block;
class HashTable {
private:
int size;
int count;
vector<int> blocks;
Block &delBlock;
public:
HashTable(int s) {
this->size = s;
this->count = 0;
this->blocks = vector<int>(this->size, NULL);
this->delBlock = NULL;
}
int hashCreator(string key, int prime) {
int hash = 0;
int len = key.size();
for(int i = 0; i < len; i++) {
hash += pow(prime, len-(i+1)) * (key[i] - 'a');
hash %= this->size
}
return hash;
}
int gethash(string key, int attempt) {
int hash_a = this->hashCreator(key, PRIME_ONE);
int hash_b = this->hashCreator(key, PRIME_TWO);
return (hash_a + (attempt * (hash_b + 1))) % this->size;
}
void insert(string key, int val) {
Block newBlock = Block({key, val});
int hash = this->gethash(key, 0);
Block block = this->blocks[hash];
int i = 0;
if (block != NULL && block.key != this->delBlock.key) {
hash = this->gethash(newBlock.key, i);
i += 1;
}
this->blocks[hash] = newBlock;
this->count += 1;
int load = this->count * 100 / this->size;
if(load > 70) this->resizeup();
}
int search(string key) {
int hash = this.gethash(key, 0);
Block block = this->blocks[hash];
int i = 1;
while(block != NULL) {
if(block.key == key) return block->value;
hash = this->getHash(block.key, i);
block = this->blocks[hash];
i++;
}
return -1;
}
void deleteBlock(string key) {
int hash = this->gethash(key, 0);
int block = this->blocks[hash];
int i = 0;
while(block != NULL) {
if(block != this.delBlock) {
this->blocks[hash] = this.delBlock;
this.count -= 1;
break;
}
hash = this->gethash(key, i);
block = this->blocks[hash];
i += 1;
}
int load = this->cout * 100 / this->size;
if(load < 10) this->resizedown();
}
void resizeup() {
this->size *= 2;
this->blocks.resize(this->size);
}
void resizedown() {
this->size = this->size / 2;
this->blocks.resize(this->size);
}
}