-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashTable.java
More file actions
95 lines (87 loc) · 2.57 KB
/
HashTable.java
File metadata and controls
95 lines (87 loc) · 2.57 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
public class HashTable
{
public int size;
public int step;
public String [] slots;
public HashTable(int sz, int stp)
{
size = sz;
step = stp;
slots = new String[size];
for(int i=0; i<size; i++) slots[i] = null;
}
public int hashFun(String value)
{
// всегда возвращает корректный индекс слота
int index = 0;
for (int i = 0; i < value.length();i++){
index +=(int)value.charAt(i);
}
if (index >= size){
return index % size;
}
else
return index;
}
public int seekSlot(String value) {
int counter = hashFun(value);
// находит индекс пустого слота для значения, или -1
if (isEmpty(slots) == 0) {
return -1;
}
while (slots[counter] != null) {
counter += step;
counter %= size;
}
return counter;
}
public int put(String value) {
// записываем значение по хэш-функции
// возвращается индекс слота или -1
// если из-за коллизий элемент не удаётся разместить
int counter = hashFun(value);
int isEmpty = isEmpty(slots);
while (slots[counter] != null) {
counter += step;
counter %= size;
if (isEmpty == 0) {
return -1;
}
}
slots[counter] = value;
return counter;
}
public int isEmpty(String [] array){
int amount = 0;
for (int i = 0; i < array.length; i++){
if (array[i] == null){
amount++;
}
}
return amount;
}
public int find(String value) {
// находит индекс слота со значением, или -1
int counter = hashFun(value);
int times = 0;
while (slots[counter] != null) {
if (slots[counter].equals(value)) {
System.out.println(value + " was found in index " + counter);
return counter;
}
counter += step;
counter %= size;
times++;
if (times == size){
return -1;
}
}
return -1;
}
public void display() {
for (int i = 0; i < size; i++){
System.out.print("| " + slots[i] + " ");
}
System.out.println("|");
}
}