-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearProbingHash.java
More file actions
49 lines (42 loc) · 1.48 KB
/
Copy pathLinearProbingHash.java
File metadata and controls
49 lines (42 loc) · 1.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
public class LinearProbingHash {
private String[] table;
private int[] collisions;
private int size;
// Constructor
public LinearProbingHash(int size) {
this.size = size;
table = new String[size];
collisions = new int[size];
}
// Insert a word into the table
public void insert(String word) {
word = word.toLowerCase();
int index = HashFunctions.basicHash(word, size);
System.out.println("Word: " + word + " | Hash = " + HashFunctions.basicHash(word, HashFunctions.m) + " | Index = " + index);
int originalIndex = index;
int collisionCount = 0;
while (table[index] != null && !table[index].equals(word)) {
collisionCount++;
index = (index + 1) % size;
if (index == originalIndex) {
System.out.println("Table is full!");
return;
}
}
if (table[index] == null) {
table[index] = word;
collisions[index] = collisionCount;
}
}
// Display the hash table
public void display() {
System.out.println("\nLinear Probing Hash Table:");
System.out.println("Index\tWord\tCollisions");
System.out.println("--------------------------");
for (int i = 0; i < size; i++) {
if (table[i] != null) {
System.out.println(i + "\t" + table[i] + "\t" + collisions[i]);
}
}
}
}