-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
110 lines (88 loc) · 2.1 KB
/
HashTable.java
File metadata and controls
110 lines (88 loc) · 2.1 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
103
104
105
106
107
108
109
110
package hashtable;
public class HashTable implements HashTableInterface {
private static final Object NO_SUCH_KEY = null;
private final Integer initialCap = 16;
private boolean usesDoubleHash;
private Object[] arr;
private Integer cap;
private Integer size;
public HashTable(boolean usesDoubleHash) {
this.arr = new Integer[initialCap];
this.size = 0;
this.cap = initialCap;
this.usesDoubleHash = usesDoubleHash;
}
public Object findElement(Integer key) {
for (int i=0; i<cap; i++) {
if (arr[i] == key) return key;
}
return NO_SUCH_KEY;
}
public void rehash() { // apos aumentar o tamanho do array ela redistribui as chaves
}
public Integer insertItem(Integer x) {
if (size == cap-1) doubleCap();
if (arr[x%size] == null) {
arr[x%size] = x;
} else if (usesDoubleHash) { // tratamento de colisão: hash duplo
int q = size;
int i = q-x%q;
if (arr[i] != null) {
i = q + 2%cap; // segundo hash
while (arr[i] != null) {
if (i == size-1) i = 0;
else i++;
}
}
arr[i] = x;
} else { // tratamento de colisão: linear probing
int i = x%7;
while (arr[i] != null) {
if (i == size-1) i = 0;
else i++;
}
arr[i] = x;
}
size++;
return x;
}
public Object removeElement(Integer key) {
System.out.println("aAAAAAAAAAAAAAAAAAAAAA!");
for (int i=0; i<cap; i++) {
if (arr[i] == key) {
Integer temp = (Integer) arr[i];
System.out.println("um!");
arr[i] = null;
System.out.println("dois!!");
size--;
return temp;
}
}
return NO_SUCH_KEY;
}
public Integer size() {
return size;
}
public Boolean isEmpty() {
return (size==0);
}
public Object[] keys() {
return arr;
}
// métodos auxiliares
private void doubleCap() {
Object [] aux = new Integer[cap*2];
for(int i=0; i<size; i++) {
aux[i] = arr[i];
}
arr = aux;
cap *= 2;
}
public void print() {
System.out.printf("[ ");
for (int i=0; i<cap; i++) {
System.out.printf("%s, ", arr[i]);
}
System.out.printf("]"); System.out.printf(" size: %d, cap: %d, isEmpty: %b%n", size(), cap, isEmpty());
}
}