-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTableQuadric.cpp
94 lines (85 loc) · 1.55 KB
/
hashTableQuadric.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
#include "hashTableQuadric.h"
void HashTableQuadric::resize(size_t newCapacity)
{
int* oldTable = table;
int oldCapacity = capacity;
size = 0;
capacity = newCapacity;
table = new int[capacity];
for (size_t i = 0; i < capacity; i++)
{
table[i] = -1;
}
for (size_t i = 0; i < oldCapacity; i++)
{
if (oldTable[i] != -1)
{
insert(i, oldTable[i]);
}
}
delete[] oldTable;
}
HashTableQuadric::HashTableQuadric(size_t capacity)
{
this->capacity = capacity;
table = new int[capacity];
for (size_t i = 0; i < capacity; i++) {
table[i] = -1;
}
size = 0;
}
HashTableQuadric::~HashTableQuadric()
{
delete[] table;
size = 0;
capacity = 0;
}
int HashTableQuadric::hash(int key)
{
return key % capacity;
}
void HashTableQuadric::insert(int key, int value)
{
int index = hash(key);
while (table[index] != -1) {
index = (index * 2) % capacity;
}
table[index] = value;
size++;
if (size >= capacity) {
resize(capacity * 2);
}
}
void HashTableQuadric::remove(int key)
{
int index = hash(key);
while (table[index] != -1) {
int value = table[index];
table[index] = -1;
size--;
index = (index * 2) % capacity;
}
if (size == capacity / 4)
resize(capacity / 2);
}
int HashTableQuadric::search(int key) {
int index = hash(key);
int startIndex = index;
do{
if (table[index] != -1) {
return table[index];
}
} while (index != startIndex);
return -1;
}
void HashTableQuadric::display()
{
for (size_t i = 0; i < capacity; i++) {
cout << i << ": ";
if (table[i] != -1) {
cout << table[i];
}
cout << endl;
}
cout << endl;
}