-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashtaple.cpp
More file actions
76 lines (64 loc) · 1.7 KB
/
Copy pathHashtaple.cpp
File metadata and controls
76 lines (64 loc) · 1.7 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "Hashtable.h"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int Hashtable::hashFunction(int number) {
return number % capacity;
}
void Hashtable::resize() {
int newCapacity = capacity * 2;
int* newTable = new int[newCapacity];
std::fill(newTable, newTable + newCapacity, -1);
for (int i = 0; i < capacity; i++) {
if (table[i] != -1) {
int newIndex = hashFunction(table[i]);
newTable[newIndex] = table[i];
}
}
delete[] table;
table = newTable;
capacity = newCapacity;
}
Hashtable::Hashtable(std::string& filename) : capacity(10), numElements(0) {
table = new int[capacity];
std::fill(table, table + capacity, -1);
std::ifstream file(filename);
int number;
while (file >> number) {
if (numElements == capacity) {
resize();
}
int index = hashFunction(number);
while (table[index] != -1) {
index = (index + 1) % capacity;
}
table[index] = number;
numElements++;
}
file.close();
}
Hashtable::~Hashtable() {
delete[] table;
}
int Hashtable::getSize() {
return numElements;
}
std::string Hashtable::search(int number) {
int index = hashFunction(number);
while (table[index] != -1 && table[index] != number) {
index = (index + 1) % capacity;
}
return (table[index] == number) ? "SUCCESS" : "FAILURE";
}
void Hashtable::insert(int number) {
if (numElements >= capacity) {
resize();
}
int index = hashFunction(number);
while (table[index] != -1) {
index = (index + 1) % capacity;
}
table[index] = number;
numElements++;
}