Created
November 11, 2019 15:52
-
-
Save parzibyte/3e6af5bd2a8d05723b0a3f3a2ce58129 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
/** | |
* Ordenar arreglos en C usando la función incorporada "qsort" | |
* | |
* @author parzibyte | |
* @see https://parzibyte.me/blog | |
* */ | |
#include <stdio.h> | |
#include <stdlib.h> | |
int funcionQueCompara(const void *a, const void *b) { | |
// Castear a enteros | |
int aInt = *(int *) a; | |
int bInt = *(int *) b; | |
// Al restarlos, se debe obtener un número mayor, menor o igual a 0 | |
// Con esto ordenamos de manera ascendente | |
return aInt - bInt; | |
} | |
int main(void) { | |
int arreglo[] = {28, 11, 96, 21, 97, 6, 18, 13, 1}; | |
int tamanioElemento = sizeof arreglo[0]; | |
int longitud = sizeof arreglo / tamanioElemento; | |
printf("Imprimendo arreglo antes de ordenar\n"); | |
for (int x = 0; x < longitud; x++) { | |
printf("%d ", arreglo[x]); | |
} | |
qsort(arreglo, longitud, tamanioElemento, funcionQueCompara); | |
printf("\nImprimendo arreglo ya ordenado\n"); | |
for (int x = 0; x < longitud; x++) { | |
printf("%d ", arreglo[x]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment