-
Notifications
You must be signed in to change notification settings - Fork 1
/
sequential.h
141 lines (115 loc) · 3.32 KB
/
sequential.h
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
136
137
138
139
140
141
#ifndef SEQUENTIAL_H
#define SEQUENTIAL_H
#include "hashtable.h"
#include <cstdio>
#define START_NUM_BUCKETS 16
#define RESIZE_FACTOR 0.75
class Node {
public:
uint32_t key, value;
Node* next;
Node(uint32_t K, uint32_t V): key(K), value(V), next(NULL){}
};
class Bucket {
public:
uint32_t size;
Node *head;
Bucket(): size(0), head(NULL) {}
~Bucket() {
Node* head = this->head;
while(head != NULL) {
Node* next = head->next;
head = next;
}
}
bool hasKey(uint32_t k) {
Node* head = this->head;
while(head != NULL) {
if(head->key == k) {
return true;
}
head = head->next;
}
//Didn't find key
return false;
}
void add(uint32_t k, uint32_t v) {
if(head == NULL) {
head = new Node(k, v);
} else {
Node* node = new Node(k, v);
node->next = head;
head = node;
}
size++;
}
uint32_t get(uint32_t k) {
Node* head = this->head;
while(head != NULL) {
if(head->key == k) {
return head->value;
}
head = head->next;
}
//Didn't find key
return 0xdeadbeef;
}
};
class Sequential: public HashTable {
private:
uint32_t num_buckets;
Bucket* buckets;
bool toresize;
//protected field entries
double balanceFactor() {
return (double) entries / (double) num_buckets;
}
Bucket* getBucketForKey(uint32_t key) {
return buckets + (hash_(key) % num_buckets);
}
void resize() {
//Save old buckets
Bucket* old_buckets = buckets;
uint32_t old_size = num_buckets;
//Make new buckets with old size
num_buckets *= 2;
buckets = new Bucket[num_buckets];
entries = 0;
//Insert all old elements into new table
for(uint32_t i = 0; i < old_size; i++) {
Bucket* b = &old_buckets[i];
Node* head = b->head;
while(head != NULL) {
put(head->key, head->value);
head = head->next;
}
}
}
public:
Sequential(bool toresize=true) : num_buckets(START_NUM_BUCKETS) {
buckets = new Bucket[START_NUM_BUCKETS];
this->toresize = toresize;
}
uint32_t get(uint32_t key) {
Bucket* b = getBucketForKey(key);
return b->get(key);
}
void put(uint32_t key, uint32_t val) {
Bucket* b = getBucketForKey(key);
b->add(key, val);
entries++;
if(toresize && balanceFactor() >= RESIZE_FACTOR) {
resize();
}
return;
}
bool hasKey(uint32_t key) {
Bucket* b = getBucketForKey(key);
//return false if bucket empty
if(b->size == 0) {
return false;
}
return b->hasKey(key);
}
};
#endif