Exemple #1
0
char * heap_remove(heap * h)
{
	int i, filho_maior;
	elemento * aux;
	char * ret;

	if (!h || h->tamanho_actual <= 0)
		return NULL;

	ret = h->elementos[RAIZ]->valor;
	free(h->elementos[RAIZ]);

	h->tamanho_actual--;
	h->elementos[RAIZ] = h->elementos[h->tamanho_actual];
	h->elementos[h->tamanho_actual] = NULL;

	i = RAIZ;

	while(FILHO_ESQ(i) < h->tamanho_actual) {
		filho_maior = FILHO_ESQ(i);
		if (FILHO_DIR(i) < h->tamanho_actual && menor_que(h->elementos[FILHO_DIR(i)], h->elementos[FILHO_ESQ(i)]))
			filho_maior = FILHO_DIR(i);

		if (menor_que(h->elementos[filho_maior], h->elementos[i])) {
			aux = h->elementos[filho_maior];
			h->elementos[filho_maior] = h->elementos[i];
			h->elementos[i] = aux;
			i = filho_maior;
		}
		else
			break;
	}
	return ret;
}
Exemple #2
0
void mostraHeap(heap *h, int indice)
{
	int i, nivel = 0;
	
	if (indice < h->tamanho_atual) 
	{
		i = indice;
		while(i > RAIZ)
		{
			i = PAI(i);
			nivel++;
		}
	
		mostraHeap(h, FILHO_ESQ(indice));

		for(i = 0; i < 3 * nivel; i++)			
			printf("     ");

		printf("%s (%d)\n",h->elementos[indice]->valor, h->elementos[indice]->prioridade);
		
		mostraHeap(h, FILHO_DIR(indice));
	}
	
	if (nivel == 0) 
		printf("\n");
}
Exemple #3
0
char * heap_remove(heap * h)
{
	int i, filho_maior;
	elemento * aux;
	char * ret;

	/* se heap estiver vazia, nao remove elemento */
	if (!h || h->tamanho_atual <= 0)
		return NULL;

	ret = h->elementos[RAIZ]->valor;
	free(h->elementos[RAIZ]);

	/* coloca ultimo elemento da heap na raiz */
	h->tamanho_atual--;
	h->elementos[RAIZ] = h->elementos[h->tamanho_atual];
	h->elementos[h->tamanho_atual] = NULL;

	i = RAIZ;

	/* enquanto nao chegar 'a base da heap */
	while(FILHO_ESQ(i) < h->tamanho_atual)
	{
		filho_maior = FILHO_ESQ(i);
		
		/* verifica se existe filho 'a direita e se este e' mais prioritario do que 'a esquerda */
		if (FILHO_DIR(i) < h->tamanho_atual && menor_que(h->elementos[FILHO_DIR(i)], h->elementos[FILHO_ESQ(i)]))
			filho_maior = FILHO_DIR(i);

		/* enquanto elemento for mais prioritario do que o respetivo pai, troca-os */
		if (menor_que(h->elementos[filho_maior], h->elementos[i]))
		{
			aux = h->elementos[filho_maior];
			h->elementos[filho_maior] = h->elementos[i];
			h->elementos[i] = aux;
			i = filho_maior;
		}
		else
			break;
	}
	
	return ret;
}