Buscar

Implementação Heap

Esta é uma pré-visualização de arquivo. Entre para ver o arquivo original

package Heap;
public class Heap {
	private int[] vetor = new int[100];
	private int counter = 0;
	
	private void up(int index) {
		int aux = (index/2);
		if(aux >= 1)
			if(vetor[index] > vetor[aux]) {
				int auxv = vetor[aux];
				vetor[aux] = vetor[index];
				vetor[index] = auxv;
				up(aux);
			}
	}
	
	private void down(int index) {
		int aux = index*2;
		if(aux <= counter) {
			if(aux < counter)
				if(vetor[aux+1] > vetor[aux])
						aux++;
			if(vetor[index] < vetor[aux]) {
				int auxv = vetor[index];
				vetor[index] = vetor[aux];
				vetor[aux] = auxv;
				down(aux);
			}
		}
	}
	
	public void add(int value) {
		if(counter < vetor.length) {
			counter++;
			vetor[counter] = value;
			up(counter);
		}
	}
	
	public void remove() {
		if(counter != 0) {
			System.out.println("removed : " + vetor[1]);
			vetor[1] = vetor[counter];
			counter--;
			down(1);
		}
	}
	
	public void show() {
		for(int i = 1;i <= counter;i++)
			System.out.print(" " + vetor[i]);
	}
}

Teste o Premium para desbloquear

Aproveite todos os benefícios por 3 dias sem pagar! 😉
Já tem cadastro?

Outros materiais