Last active
July 7, 2022 14:20
-
-
Save salluzziluca/2901f27dde79ceacc141e03a32b57b32 to your computer and use it in GitHub Desktop.
heapify
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 swap(int*vector,int pos1,int pos2) | |
{ | |
int aux=vector[pos1]; | |
vector[pos1]=vector[pos2]; | |
vector[pos2]=aux; | |
} | |
void sift_down(struct heap*heap,int n) | |
{ | |
int hijo_izquierdo = 2*n+1; | |
int hijo_derecho = 2*n+2; | |
if(hijo_izquierdo >= heap->tamanio) | |
return; | |
int hijo_mas_grande = hijo_izquierdo; | |
if(hijo_derecho < heap->tamanio){ | |
if(heap->vector[hijo_derecho] > heap->vector[hijo_izquierdo]) | |
hijo mas grande=hijo_derecho; | |
} | |
if(heap->vector[n] < heap->vector[hijo_mas_grande]){ | |
swap(heap->vector,n,hijo_mas_grande); | |
sift_down(heap,hijo_mas_grande); | |
} | |
} | |
void sift_up(struct heap*heap,int n) | |
{ | |
if(n==0) | |
return; | |
int padre = (n-1)/2; | |
if(heap->vector[n] > heap->vector[padre]){ | |
swap(heap->vector,n,padre); | |
sift_up(heap,padre); | |
} | |
} | |
void extraer_raiz(int *vector, int* tope){ | |
if(tope == 0) | |
return 0; | |
int valor = vector[0]; | |
swap(vector,0,tope-1); | |
(*tope)--; | |
} | |
void heapify(int*vector,int tope, bool ascendente) | |
{ | |
int actual=tope-1; | |
while(actual>=0){ | |
if(ascendente) | |
sift_down(vector,actual); | |
else | |
sift_up(vector,actual); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment