What do you think of my code ? I implemented this in C using qsort
, but I’m not sure about the reliability and correctness. And can I make it faster? I call this piece of code a lot.
#include <stdio.h> #include <stdlib.h> #include <time.h> #define DIM 1 #define POWDIM 4 typedef unsigned long keytype; typedef struct{ keytype k; int idx; }sort_child; int compare(const void *a, const void *b){ const keytype *x = a, *y = b; if(*x > *y) return 1; else return (*x < *y) ? -1 : 0; } int main(int argc, char **argv){ srand(time(NULL)); sort_child sc[POWDIM]; printf("Before qsort()\n"); for(int i=0; i<POWDIM; i++){ sc[i].k = rand()%100; sc[i].idx = i; printf("sc[%d].k = %lu sc[%d].idx = %d\n", i, sc[i].k, i, sc[i].idx); } qsort (sc, POWDIM, sizeof(sort_child), compare); printf("\n"); printf("After qsort()\n"); for(int i=0; i<POWDIM; i++){ printf("sc[%d].k = %lu sc[%d].idx = %d\n", i, sc[i].k, i, sc[i].idx); } }