-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTableDouble.java
136 lines (109 loc) · 3.2 KB
/
HashTableDouble.java
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package javaAlgorithms;
import java.util.Random;
class Items {
private int data;
public Items (int data) {
this.data = data;
}
public int getKey() {
return this.data;
}
}
class HashTables {
private Items [] hashArr;
private int arrSize;
private Items nonItem;
public HashTables (int size) {
this.arrSize = size;
hashArr = new Items[arrSize];
nonItem = new Items(-1);
}
public void display () {
for (int i = 0; i < arrSize; i++) {
if (hashArr[i] != null) {
System.out.println(hashArr[i].getKey());
} else {
System.out.println("***");
}
}
}
//двойное хэширование
public int hashFunc (int key) {
return (key % arrSize);
}
public int hashFuncDouble (int key) {
return (5 - key % 5);
}
public void insert (Items item) {
int key = item.getKey();
int hashVal = hashFunc(key);
int stepSize = hashFuncDouble(key);
while (hashArr[hashVal] != null && hashArr[hashVal].getKey() != -1){
hashVal += stepSize;
hashVal %= arrSize;
}
hashArr[hashVal] = item;
}
//увеличение хэш-таблицы
private int getPrime (int min) {
for (int i = min+1; true; i++){
if (isPrime(i));
return i;
}
}
private boolean isPrime (int n){
for (int j = 2; (j*j <= n); j++)
if (n % j == 0)
return false;
return true;
}
public Items delete (int key) {
int hashVal = hashFunc(key);
while (hashArr [hashVal] != null){
if (hashArr[hashVal].getKey() == key){
Items temp = hashArr[hashVal];
hashArr[hashVal] = nonItem;
return temp;
}
++hashVal;
hashVal %= arrSize;
}
return null;
}
public Items find (int key) {
int hashVal = hashFunc(key);
while (hashArr [hashVal] != null) {
if (hashArr[hashVal].getKey() == key){
return hashArr[hashVal];
}
++hashVal;
hashVal %= arrSize;
}
return null;
}
}
public class HashTableDouble {
public static void hashFunc2 (int k, int ize) {
System.out.println(k % ize);
}
public static void main(String[] args) {
Items aDataItem;
int aKey;
int size = 66;
HashTables hTable = new HashTables(size);
Random rand = new Random();
for (int j = 0; j < 15; j++){
aKey = rand.nextInt(999);
aDataItem = new Items(aKey);
hTable.insert(aDataItem);
}
hTable.insert(new Items(999));
hTable.insert(new Items(203));
hTable.display();
hashFunc2(999,66);
System.out.println(hTable.find(999).getKey());
hTable.delete(203);
System.out.println("Повторный прогон");
hTable.display();
}
}