I'm in doubt about the heap priority queue, regarding inserting elements in this list.
Does each heap start by inserting the element vetor[1]
? Or should you enter from vetor[0]
? Because I have a heap that inserts into vetor[1]
, because if you insert in vetor[0]
, of the problem when uploading.
public class Heap {
int[] T = new int[100];
int n; //equivalente ao Tam
public void inserir(int chave) {
T[n + 1] = chave; //n + 1?
++n;
subir(n);
}
public void subir(int n) {
int j = n / 2;
if(j >= 1) { //verifica se tem mais de um elemneto no vetor
if(T[n] > T[j]) {
int temp = T[n];
T[n] = T[j];
T[j] = temp;
subir(j);
}
}
}
public void remover() {
if(n != 0) { //se o array nao esta vazio
T[1] = T[n]; //remove o de maior prioridade, recebe o ultimo no da esquerda
T[n] = 0;
--n;
descer(1, n);
}
}
public void descer(int j, int n) {
int i = 2 * j;
if(i <= n) {
if(i < n) {
if(T[i + 1] > T[i]) {
i++;
}
}
if(T[j] < T[i]) {
int temp = T[i];
T[i] = T[j];
T[j] = temp;
descer(i, n);
}
}
}
public void imprimir() {
for(int i = 1; i <= n; i++) {
System.out.println(T[i]);
}
}
}