-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.cpp
More file actions
90 lines (78 loc) · 2.26 KB
/
HashTable.cpp
File metadata and controls
90 lines (78 loc) · 2.26 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class HashTable {
private:
vector<string> table;
int size;
int hashFunction(const string &word) {
// Using ASCII values and multiply powers
return (static_cast<int>(word[0]) * 31 + static_cast<int>(word[1])) % size;
}
public:
HashTable(int size) : size(size) {
table.resize(size, "");
}
void insert(const string &word) {
int index = hashFunction(word);
int originalIndex = index;
// Linear probing to handle collisions
while (!table[index].empty()) {
index = (index + 1) % size;
if (index == originalIndex) {
throw runtime_error("Hash table is full");
}
}
table[index] = word;
}
int search(const string &word) {
int index = hashFunction(word);
int originalIndex = index;
while (!table[index].empty()) {
if (table[index] == word) {
return index;
}
index = (index + 1) % size;
if (index == originalIndex) {
return -1; // Word not found
}
}
return -1; // Word not found
}
void display() {
for (int i = 0; i < size; ++i) {
if (!table[i].empty()) {
cout << i << ": " << table[i] << endl;
}
}
}
};
int main() {
HashTable hashTable(200);
vector<string> words = {
"fg", "ask", "fk", "re", "dl", "w", "dk", "gf", "hk", "ik"
// Add all 80 words here
};
for (const auto &word : words) {
hashTable.insert(word);
}
// Display the hash table
hashTable.display();
// Search for words
string searchWord = "ask";
int index = hashTable.search(searchWord);
if (index != -1) {
cout << "Index of '" << searchWord << "': " << index << endl;
} else {
cout << "'" << searchWord << "' not found in the hash table." << endl;
}
searchWord = "zk";
index = hashTable.search(searchWord);
if (index != -1) {
cout << "Index of '" << searchWord << "': " << index << endl;
} else {
cout << "'" << searchWord << "' not found in the hash table." << endl;
}
return 0;
}