-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHashRehash.java
101 lines (84 loc) · 2.54 KB
/
HashRehash.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
//===========//
//HASH REHASH//
//===========//
// METODOS: hash -> insert -> search -> remove
package Hashing;
public class HashRehash {
final int EMPTY = -1; // flag de index vazio
int table[]; // tabela
int t; // tamanho da tabela
// cria a tabela
public HashRehash(){
this(13);
}
// PREENCHE a tabela com indices VAZIOS
public HashRehash(int t){
this.t = t;
this.table = new int[this.t];
for (int i = 0; i < t; i++){
table[i] = EMPTY;
}
}
//=====HASH=====//
public int hash(int x){
return x % t;
}
public int rehash(int x){
return ++x % t;
}
//=====HASH=====//
//=====INSERT=====//
public boolean insert(int x){
boolean result = false;
if (x != EMPTY){
// calcula index com o hash
int id = hash(x);
// INSERE DIRETO na tabela se o index dela estiver VAZIO
if (table[id] == EMPTY){
table[id] = x;
result = true;
}
// senao, realiza o REHASH e o adiciona se indice estiver VAZIO
else {
id = rehash(x);
if (table[id] == EMPTY){
table[id] = x;
result = true;
}
}
}
return result;
}
//=====INSERT=====//
//=====SEARCH=====//
public int search(int x){
int result = EMPTY;
// calcula index com o hash
int id = hash(x);
// se encontrado no PRIMEIRO HASH
if (table[id] == x) result = id;
// senao, busca no REHASH
else if (table[id] != EMPTY){
id = rehash(x);
// se encontrado no REHASH
if (table[id] == x){
result = id;
}
}
// retorna o INDICE
return result;
}
//=====SEARCH=====//
//=====REMOVE=====//
public boolean remove(int x){
boolean result = false;
// realiza a PESQUISA
int id = search(x);
// se o elemento EXISTIR nas tabelas, o REMOVE
if (id != EMPTY){
table[id] = EMPTY;
}
return result;
}
//=====REMOVE=====//
}