forked from codingCapricorn/Hactoberfest-2020-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash Table Quadratic Probing.txt
73 lines (59 loc) · 1.38 KB
/
Hash Table Quadratic Probing.txt
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
#include <iostream>
#define SIZE 10
using namespace std;
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
int Hash(int key){
return key % SIZE;
}
int QuadraticProbe(int H[], int key){
int idx = Hash(key);
int i = 0;
while (H[(idx+i*i) % SIZE] != 0){
i++;
}
return (idx + i*i) % SIZE;
}
void Insert(int H[], int key){
int idx = Hash(key);
if (H[idx] != 0){
idx = QuadraticProbe(H, key);
}
H[idx] = key;
}
int Search(int H[], int key){
int idx = Hash(key);
int i = 0;
while (H[(idx+i*i) % SIZE] != key){
i++;
if (H[(idx + i*i) % SIZE] == 0){
return -1;
}
}
return (idx + i*i) % SIZE;
}
int main() {
int A[] = {26, 30, 45, 23, 25, 43, 74, 19, 29};
int n = sizeof(A)/sizeof(A[0]);
Print(A, n, " A");
// Hash Table
int HT[10] = {0};
for (int i=0; i<n; i++){
Insert(HT, A[i]);
}
Print(HT, SIZE, "HT");
int index = Search(HT, 25);
cout << "key found at: " << index << endl;
index = Search(HT, 35);
cout << "key found at: " << index << endl;
return 0;
}