Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created November 11, 2019 15:52
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 parzibyte/3e6af5bd2a8d05723b0a3f3a2ce58129 to your computer and use it in GitHub Desktop.
Save parzibyte/3e6af5bd2a8d05723b0a3f3a2ce58129 to your computer and use it in GitHub Desktop.
/**
* 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