-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDouble Hashing
113 lines (95 loc) · 2.46 KB
/
Double Hashing
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <bits/stdc++.h>
using namespace std;
// Hash table size
#define TABLE_SIZE 13
// Used in second hash function.
#define PRIME 7
class DoubleHash
{
// Pointer to an array containing buckets
int *hashTable;
int curr_size;
public:
// function to check if hash table is full
bool isFull()
{
// if hash size reaches maximum size
return (curr_size == TABLE_SIZE);
}
// function to calculate first hash
int hash1(int key)
{
return (key % TABLE_SIZE);
}
// function to calculate second hash
int hash2(int key)
{
return (PRIME - (key % PRIME));
}
DoubleHash()
{
hashTable = new int[TABLE_SIZE];
curr_size = 0;
for (int i=0; i<TABLE_SIZE; i++)
hashTable[i] = -1;
}
// function to insert key into hash table
void insertHash(int key)
{
// if hash table is full
if (isFull())
return;
// get index from first hash
int index = hash1(key);
// if collision occurs
if (hashTable[index] != -1)
{
// get index2 from second hash
int index2 = hash2(key);
int i = 1;
while (1)
{
// get newIndex
int newIndex = (index + i * index2) %
TABLE_SIZE;
// if no collision occurs, store
// the key
if (hashTable[newIndex] == -1)
{
hashTable[newIndex] = key;
break;
}
i++;
}
}
// if no collision occurs
else
hashTable[index] = key;
curr_size++;
}
// function to display the hash table
void displayHash()
{
for (int i = 0; i < TABLE_SIZE; i++)
{
if (hashTable[i] != -1)
cout << i << " --> "
<< hashTable[i] << endl;
else
cout << i << endl;
}
}
};
// Driver's code
int main()
{
int a[] = {19, 27, 36, 10, 64};
int n = sizeof(a)/sizeof(a[0]);
// inserting keys into hash table
DoubleHash h;
for (int i = 0; i < n; i++)
h.insertHash(a[i]);
// display the hash Table
h.displayHash();
return 0;
}