-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
102 lines (82 loc) · 2.6 KB
/
Heap.java
File metadata and controls
102 lines (82 loc) · 2.6 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
package aed;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.ArrayList;
import java.util.Comparator;
public class Heap<T> {
private ArrayList<T> datos;
private Comparator<T> comparador;
private int cantidad;
public Heap(Comparator<T> comparador) {
datos = new ArrayList<>();
this.comparador = comparador;
}
public Heap(T[] datos, Comparator<T> comparador) {
this.datos = heapify(datos, comparador);
this.comparador = comparador;
}
private ArrayList<T> heapify(T[] datos, Comparator<T> comparador) {
throw new NotImplementedException();
}
public void agregar(T elemento) {
if (cantidad >= datos.size()) {
datos.add(elemento);
}
else {
datos.set(cantidad,elemento);
}
subir(cantidad);
cantidad++;
}
public T primero() {
return datos.get(0);
}
public void eliminar() {
throw new NotImplementedException();
}
private void subir(int indice) {
if (indice == 0) return;
int indicePadre = indicePadre(indice);
T elemento = datos.get(indice);
T padre = datos.get(indicePadre);
if (comparador.compare(elemento,padre) > 0 ) {
intercambiar(indice,indicePadre);
}
}
private void bajar(int indice) {
int indiceIzquierdo = indiceIzquierdo(indice);
int indiceDerecho = indiceDerecho(indice);
if (!enRango(indiceIzquierdo)) return;
T elemento = datos.get(indice);
T hijoIzquierdo = datos.get(indiceIzquierdo);
T hijoDerecho = datos.get(indiceDerecho);
if (enRango(indiceDerecho) && esMenor(hijoIzquierdo,hijoDerecho) && esMenor(elemento,hijoDerecho)) {
intercambiar(indice,indiceDerecho);
bajar(indiceDerecho);
return;
}
if (esMenor(elemento,hijoIzquierdo)) {
intercambiar(indice,indiceIzquierdo);
bajar(indiceIzquierdo);
}
}
private boolean enRango(int indice) {
return indice < cantidad;
}
private boolean esMenor(T t1, T t2) {
return comparador.compare(t1,t2) < 0;
}
private int indicePadre(int index) {
return index / 2;
}
private int indiceIzquierdo(int index) {
return (2 * index) + 1;
}
private int indiceDerecho(int index) {
return (2 * index) + 2;
}
private void intercambiar(int index1, int index2) {
T temp = datos.get(index1);
datos.set(index1, datos.get(index2));
datos.set(index2,temp);
}
}