Created
May 17, 2015 17:54
-
-
Save luccasiau/5c3ad445af32500facdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void heapify_up(int v){ | |
if(v == 1) return; // se estivermos no topo, fazemos mais nada | |
int p = pai(v); | |
if(heap[v] > heap[p]){ | |
// se o valor da posição v for maior que o de seu pai, | |
// temos que fazer a troca dos dois e chamar a função em p | |
swap(heap[v], heap[p]); | |
heapify_up(p); | |
} | |
} | |
void heapify_down(int v){ | |
int d = direita(v); | |
int e = esquerda(v); | |
int maior = v; // no fim, maior terá a maior das posições | |
// comparamos com cada um dos filhos. | |
// temos que checar, também, se os filhos existem | |
if(d <= tamanho_heap && heap[d] > heap[v]) maior = d; | |
if(e <= tamanho_heap && heap[e] > heap[maior]) maior = e; | |
if(maior != v){ | |
// se v não for o maior, temos que trocar com o maior dos filhos | |
// e chamamos a função para ele | |
swap(heap[v], heap[maior]); | |
heapify_down(maior); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment