-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashTable.java
More file actions
58 lines (48 loc) · 1.47 KB
/
HashTable.java
File metadata and controls
58 lines (48 loc) · 1.47 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
package calc;
public class HashTable {
int max_size = 100;
UserDefined hash_arr[] = new UserDefined[max_size];
//hash function
int generate_hash(String var) {
long hash = 1;
int p = 53;
int m = (int) (1e5 + 9);
long pow_p = 1;
for (int i = 0; i < var.length(); i++) {
hash = (hash + (var.charAt(i) - 'a' + 1) * pow_p) % m;
pow_p = (pow_p * p) % m;
}
return (int)(hash % max_size);
}
void insert(UserDefined var) {
int hash = generate_hash(var.name);
if (hash_arr[ hash] != null) {
// collision
int i = 1;
while (hash_arr[hash] != null) {
hash = (hash + i * i) % max_size; //quadratic probing
i++;
}
}
hash_arr[hash] = var;
}
UserDefined search(String var_name) {
int hash = generate_hash(var_name);
if (hash_arr[hash] != null && hash_arr[hash].name.equals(var_name)) {
return (hash_arr[hash]);
}
else
{
int n = 0;
int i = 0;
while (n < max_size)
{
hash = (hash + i * i) % max_size;
if (hash_arr[hash] != null && hash_arr[hash].name.equals(var_name))
return (hash_arr[hash]);
n++;
}
return (null);
}
}
}