typestar

qsort con comparador en C

El ordenamiento estándar recibe el tamaño del elemento y una función de comparación.

#include <stdlib.h>
#include <string.h>

static int by_int(const void *a, const void *b) {
    int x = *(const int *) a;
    int y = *(const int *) b;
    return (x > y) - (x < y);
}

static int by_length(const void *a, const void *b) {
    size_t x = strlen(*(const char *const *) a);
    size_t y = strlen(*(const char *const *) b);
    return (x > y) - (x < y);
}

void sort_both(int *nums, size_t n, const char **words, size_t w) {
    qsort(nums, n, sizeof(int), by_int);
    qsort(words, w, sizeof(char *), by_length);
}

Cómo funciona

  1. El comparador recibe const void * y los castea de vuelta.
  2. Devuelve negativo, cero o positivo — no un bool.
  3. Nunca restes: size_t se desborda por abajo e int puede desbordarse.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
494
Tokens
168
Ritmo de tres estrellas
95 tpm

Al ritmo de tres estrellas de 95 tokens por minuto, este intento toma unos 106 segundos.

Escribe este fragmento

Paso 4 de 4 en Punteros genéricos y a funciones; paso 9 de 25 en Punteros y memoria.

← Anterior Siguiente →