-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_table_二次探查法.cpp
78 lines (75 loc) · 1.95 KB
/
hash_table_二次探查法.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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int HASH_SIZE = 13;
class HashTable {
private:
int table[HASH_SIZE];
int myhash(int value) const { return value % HASH_SIZE; }
public:
HashTable() { clear(); }
void clear() {
for (int i = 0; i < HASH_SIZE; i++) {
table[i] = INT_MAX;
}
}
bool insert(const int &data) {
/* 二次探查法 */
int hashValue = myhash(data);
int increment = 1;
int probeCount = 0;
while (probeCount++ < (HASH_SIZE + 1) / 2) {
if (table[hashValue] == INT_MAX || table[hashValue] == data) {
table[hashValue] = data;
return true;
} else {
hashValue = (hashValue + increment) % HASH_SIZE;
increment += 2;
}
}
return false;
}
const int &operator[](const int &data) const {
int hashValue = myhash(data);
int increment = 1;
int probeCount = 0;
while (probeCount++ < (HASH_SIZE + 1) / 2) {
if (table[hashValue] == data) {
return data;
} else {
hashValue = (hashValue + increment) % HASH_SIZE;
increment += 2;
}
}
return INT_MAX;
}
void print() const {
for (int i = 0; i < HASH_SIZE; i++) {
if (table[i] != INT_MAX) {
cout << table[i] << " ";
} else {
cout << "X ";
}
}
cout << endl;
}
};
int main() {
HashTable test;
test.insert(26);
test.insert(15);
test.print();
cout << test[26] << endl;
cout << test[13] << endl;
test.insert(16);
test.insert(33);
test.insert(100);
test.insert(0);
test.insert(28);
test.print();
cout << test[100] << endl;
cout << test[99] << endl;
cout << test[28] << endl;
system("pause");
}