Skip to content

Instantly share code, notes, and snippets.

@luccasiau
Created May 17, 2015 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luccasiau/5c3ad445af32500facdc to your computer and use it in GitHub Desktop.
Save luccasiau/5c3ad445af32500facdc to your computer and use it in GitHub Desktop.
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