Skip to content

Instantly share code, notes, and snippets.

@danlamanna
Created December 5, 2014 07:05
Show Gist options
  • Save danlamanna/538e585ee1df4d8e28c6 to your computer and use it in GitHub Desktop.
Save danlamanna/538e585ee1df4d8e28c6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int level;
} node;
int compare_nodes(const void * a, const void * b) {
int a_lvl = (*(node **)a)->level;
int b_lvl = (*(node **)b)->level;
if (a_lvl < b_lvl)
return -1;
else if (b_lvl > a_lvl)
return 1;
else
return 0;
}
int main(int argc, char *argv[]) {
int i;
node **nodes = malloc(sizeof(node *) * 5);
for (i=0;i<5;i++) {
nodes[i] = malloc(sizeof(node));
nodes[i]->level = 5-i;
}
for (i=0;i<5;i++) {
printf("%d\n", nodes[i]->level);
}
// prints 5, 4, 3, 2, 1
qsort(nodes, 5, sizeof(node *), compare_nodes);
for (i=0;i<5;i++) {
printf("%d\n", nodes[i]->level);
}
// still prints 5, 4, 3, 2, 1
// expecting 1, 2, 3, 4, 5
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment