-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.cpp
More file actions
60 lines (54 loc) · 1.39 KB
/
HashTable.cpp
File metadata and controls
60 lines (54 loc) · 1.39 KB
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
#include "HashTable.h"
#include "Exception.h"
void HashTable::Grow()
{
std::shared_ptr<Array<List<Course>>> newTable(new Array<List<Course>>(2*table->GetSize()));
ReHash(table, newTable);
table = newTable;
}
void HashTable::Shrink()
{
std::shared_ptr<Array<List<Course>>> newTable(new Array<List<Course>>(table->GetSize()/2));
ReHash(table, newTable);
table = newTable;
}
void HashTable::ReHash(std::shared_ptr<Array<List<Course>>> oldTable, std::shared_ptr<Array<List<Course>>> newTable)
{
int oldSize = oldTable->GetSize();
int newSize = newTable->GetSize();
for (int i = 0; i < oldSize; ++i) {
List<Course> &list = (*oldTable)[i];
for (const Course &course:list) {
(*newTable)[course.id % newSize].PushFront(course);
}
}
}
void HashTable::Insert(Course &course)
{
if (Exists(course.id)) {
throw ItemFound();
}
if (numOfItems == table->GetSize()/2) {
Grow();
}
int index = Hash(course.id);
(*table)[index].PushFront(course);
++numOfItems;
}
void HashTable::Remove(int id)
{
int index = Hash(id);
if (!(*table)[index].PopItem(Course(id))) {
throw ItemNotFound();
}
}
Course& HashTable::GetCourse(int id)
{
int index = Hash(id);
for (Course& course:(*table)[index]) {
if (course.id == id) {
return course;
}
}
throw ItemNotFound();
}