O documento descreve uma classe Java chamada HeapMinMax que implementa uma heap binária mínima-máxima. A classe contém métodos para inserir, consultar, remover e listar elementos da heap, além de métodos auxiliares para manter a estrutura de heap.
Responde ou passa na HISTÓRIA - REVOLUÇÃO INDUSTRIAL - 8º ANO.pptx
Heap Mínimo e Máximo
1. C:UserselainDocumentsNetBeansProjectsHeapMinMaxsrcheapminmaxHeapMinMax.java
1 package heapminmax;
2
3 import java.util.Scanner;
4
5 public class HeapMinMax {
6
7 static int vetor[] = new int[11];
8 static int tamanho;
9
10 public static void main(String[] args) {
11 int op, mp, numero;
12 tamanho = 0;
13 Scanner s = new Scanner(System.in);
14 do {
15 System.out.println(" | MENU | ");
16 System.out.println(" | 1. Inserir | ");
17 System.out.println(" | 2. Consultar a menor prioridade | ");
18 System.out.println(" | 3. Consultar a maior prioridade | ");
19 System.out.println(" | 4. Remover maior prioridade | ");
20 System.out.println(" | 5. Remover menor prioridade | ");
21 System.out.println(" | 6. Listar | ");
22 System.out.println(" | 7. Sair | ");
23 System.out.println("");
24 System.out.print("Digite a opção desejada: ");
25 op = s.nextInt();
26 System.out.println("");
27 switch (op) {
28
29 case 1:
30 System.out.println(" == INSERINDO NA HEAP == ");
31 if (tamanho <= vetor.length) {
32 System.out.print(" Digite um número: ");
33 numero = s.nextInt();
34 tamanho++;
35 inserir(numero, tamanho);
36 System.out.println(" Número inserido com sucesso!! ");
37 System.out.println("");
38 } else {
39 System.out.println(" HEAP LOTADA!!! ");
40 System.out.println("");
41 }
42 break;
43
44 case 2:
45 System.out.println(" == MENOR PRIORIDADE == ");
46 if (tamanho == 0) {
47 System.out.println(" HEAP VAZIA! ");
48 } else {
49 System.out.println(" O elemento de menor prioridade é: " + vetor[1]);
50 System.out.println("");
51 }
52 break;
53
HeapMinMax.java file:///C:/Users/elain/HeapMinMax.html
1 de 6 09/09/2016 22:15
2. 54 case 3:
55 System.out.println(" == MAIOR PRIORIDADE == ");
56 if (tamanho == 0) {
57 System.out.println(" HEAP VAZIA! ");
58 } else {
59 mp = maiorPrioridade();
60 System.out.println(" O elemento de maior prioridade é: " + vetor[mp]);
61 System.out.println("");
62 }
63 break;
64
65 case 4:
66 System.out.println(" == REMOVER MENOR == ");
67 if (tamanho == 0) {
68 System.out.println(" HEAP VAZIA! ");
69 } else {
70 System.out.println(" O menor elemento removido é: " + vetor[1]);
71 System.out.println("");
72 vetor[1] = vetor[tamanho];
73 tamanho--;
74 descer(1);
75 }
76 break;
77
78 case 5:
79 System.out.println(" == REMOVER MAIOR == ");
80 if (tamanho == 0) {
81 System.out.println(" HEAP VAZIA! ");
82 System.out.println("");
83 } else if (tamanho == 2) {
84 tamanho = 1;
85 } else {
86 int max = 2;
87 if (tamanho >= 3) {
88 if (vetor[3] > vetor[2]) {
89 max = 3;
90 }
91 }
92 System.out.println(" O maior elemento removido é: " + vetor[max]);
93 System.out.println("");
94 vetor[max] = vetor[tamanho];
95 tamanho--;
96 descer(max);
97 }
98 break;
99
100 case 6:
101 int i;
102 System.out.println(" == Imprimindo todos os elementos da HEAP == ");
103 for (i = 0; i < tamanho + 1; i++) {
104 System.out.println(" | Posicão: " + i + " | Elemento: " + vetor[i] + " | ");
105 }
106 System.out.println("");
107 break;
108
109 case 7:
HeapMinMax.java file:///C:/Users/elain/HeapMinMax.html
2 de 6 09/09/2016 22:15
3. 110 break;
111
112 default:
113 System.out.println(" | OPÇÃO INVÁLIDA | ");
114 System.out.println("");
115 }
116
117 } while (op != 7);
118 }
119
120 private static void inserir(int numero, int i) {
121 vetor[i] = numero;
122 subir(i);
123 }
124
125 private static int maiorPrioridade() {
126 if (tamanho == 1) {
127 return 1;
128 } else if ((tamanho > 2) && (vetor[3] > vetor[2])) {
129 return 3;
130 } else {
131 return 2;
132 }
133 }
134
135 private static void subir(int i) {
136 //é o índice do possível pai
137 int pai = i / 2;
138 //verifica se o nó I encontra-se em um nível mínimo
139 if (minimo(i)) {
140 //verifica se o elemento de nível mínimo é maior que o pai
141 if (pai >= 1) {
142 if (vetor[i] > vetor[pai]) {
143 trocar(i, pai);
144 subirMax(pai);
145 } else {
146 subirMin(i);
147 }
148 }
149 } else //verifica se o elemento de nível máximo é menor que o pai
150 if (pai >= 1) {
151 if (vetor[i] < vetor[pai]) {
152 trocar(i, pai);
153 subirMin(pai);
154 } else {
155 subirMax(i);
156 }
157 }
158 }
159
160 //MÉTODO PARA SUBIR O MÁXIMO
161 private static void subirMax(int i) {
162 //índice do provável avô
163 int avo = i / 4;
164 //verifica se o elemento atual é maior que o avô
165 if ((avo >= 1) && (vetor[i] > vetor[avo])) {
HeapMinMax.java file:///C:/Users/elain/HeapMinMax.html
3 de 6 09/09/2016 22:15
4. 166 trocar(i, avo);
167 subirMax(avo);
168 }
169 }
170
171 //MÉTODO PARA SUBIR O MÍNIMO
172 private static void subirMin(int i) {
173 //indice do provável avô
174 int avo = i / 4;
175 //verifica se o elemento atual é menor que o avô
176 if ((avo >= 1) && (vetor[i] < vetor[avo])) {
177 trocar(i, avo);
178 subirMin(avo);
179 }
180 }
181
182 private static void descer(int i) {
183 if (minimo(i)) {
184 descerMin(i);
185 } else {
186 descerMax(i);
187 }
188 }
189
190 private static void descerMin(int i) {
191 //i tem filhos
192 if (2 * 1 <= tamanho) {
193 //menor dos descendentes entre filhos e netos
194 int m = minDescendente(i);
195 if (vetor[i] > vetor[m]) {
196 trocar(i, m);
197 if (m >= 4 * 1) {
198 int p = m / 2;
199 if (vetor[p] < vetor[m]) {
200 trocar(p, m);
201 }
202 descerMin(m);
203 }
204 }
205 }
206 }
207
208 private static void descerMax(int i) {
209 //i tem filhos
210 if (2 * i <= tamanho) {
211 int m = maxDescendente(i);
212 if (vetor[i] < vetor[m]) {
213 trocar(i, m);
214 if (m >= 4 * i) {
215 //p é o pai
216 int p = m / 2;
217 if (vetor[p] > vetor[m]) {
218 trocar(p, m);
219 }
220 descerMax(m);
221 }
HeapMinMax.java file:///C:/Users/elain/HeapMinMax.html
4 de 6 09/09/2016 22:15
5. 222 }
223 }
224 }
225
226 private static boolean minimo(int i) {
227 int nivel = ((int) (Math.log(i) / Math.log(2))) + 1;
228 if (nivel % 2 == 0) {
229 return false;
230 } else {
231 return true;
232 }
233 }
234
235 private static void trocar(int x, int y) {
236 //método que troca o valor entre duas posições do vetor - heap
237 int temp;
238 temp = vetor[x];
239 vetor[x] = vetor[y];
240 vetor[y] = temp;
241 }
242
243 private static int minDescendente(int i) {
244 //retorna o índice do menor dos descendentes entre filhos e netos do elemento i
245 //índice do menor elemento
246 int m = 0;
247 if (2 * i <= tamanho) {
248 //índice do menor - primeiro filho
249 m = 2 * i;
250 //verifica o menor filho
251 if (vetor[m + 1] < vetor[m]) {
252 m = m + 1;
253 }
254 //verifica o menor neto
255 for (int k = 4 * i; ((k <= 4 * i + 3) && (k <= tamanho)); k++) {
256 if (vetor[k] < vetor[m]) {
257 m = k;
258 }
259 }
260 }
261 return m;
262 }
263
264 private static int maxDescendente(int i) {
265 //retorna o índice do maior dos descendentes entre filhos e netos do elemento i
266 //índice do maior elemento
267 int m = 0;
268 if (2 * i <= tamanho) {
269 //índice do maior - primeiro filho
270 m = 2 * i;
271 if (vetor[m + 1] > vetor[m]) {
272 m = m + 1;
273 }
274 for (int k = 4 * i; ((k <= 4 * i + 3) && (k <= tamanho)); k++) {
275 if (vetor[k] > vetor[m]) {
276 m = k;
277 }
HeapMinMax.java file:///C:/Users/elain/HeapMinMax.html
5 de 6 09/09/2016 22:15