-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuadraticProbingHash.java
More file actions
102 lines (77 loc) · 2.48 KB
/
QuadraticProbingHash.java
File metadata and controls
102 lines (77 loc) · 2.48 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
91
92
93
94
95
96
97
98
99
100
101
102
public class QuadraticProbingHash implements HashInterface {
Record[] table;
int collisions;
public static class Record {
Integer key;
Integer value;
public Record(final Integer key1, final Integer value1) {
key = key1;
value = value1;
}
}
public QuadraticProbingHash(int initialSize) {
table = new Record[initialSize];
collisions = 0;
}
@Override
public Integer get(final Integer key) {
final int index = lookUp(key);
if (index > table.length) {
return null;
}
Record p = table[index];
return p.value;
}
@Override
public void put(final Integer key, final Integer value) throws RuntimeException {
final int index = lookUp(key);
if (index > table.length) {
throw new RuntimeException("Table is full");
}
Record p = table[index];
if (p == null) {
table[index] = new Record(key, value);
} else {
p.value = value;
}
}
@Override
public final int getCollisions() {
return collisions;
}
private static int hash(final Integer key) {
return (key >> 8) | ((key&0xff)<<16);
}
private int hashIndex(final Integer key) {
final int index = hash(key);
return index % table.length;
}
public String printTable(String description){
String output = "\n\n*** Begin Quadratic Probing " + description + "**** \nPrint table_.size() = " + table.length;
int i = 0;
for(Record r: this.table)
{ if(r != null)
output += ("\nIndex=" + i++ + " key=" + r.key + " value=" + r.value);
if(r == null)
output += ("\nIndex=" + i++ + " key=" + "NULL" + " value=" + "NULL");
}
return output += "\nQuadratic Probing Collisions: " + this.getCollisions();
}
private int lookUp(Integer key) {
final int startIndex = hashIndex(key);
int index = startIndex;
int i = 0;
while (true) {
final Record p = table[index];
if (p == null || p.key.equals(key)) {
return index;
}
collisions ++;
i++;
index = ((i * i) + startIndex) % table.length;
if (index == startIndex) {
return table.length + 1;
}
}
}
}