Position of first element in Heap object

Asked

Viewed 143 times

0

I’m in doubt about the priority line heap, with regard to inserting items in that list.

Every heap starts by inserting from the element vetor[1]? Or you must insert from vetor[0]? 'Cause I got a heap that inserts into the vetor[1], because insert yourself in vetor[0], of the problem in time to rise.

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]);
        }
    }

}
  • 1

    Needs the code.

  • There’s the code, buddy.

  • Where did this code come from? Did you make it? If not, what is the source?

  • Whoever wrote this code assumed it was worth squandering a position. Not all implementations need to do this

  • Source: http://www.gpec.ucdb.br/pistori/disciplinas/ed/aulas_I/lp.htm

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.