Created
December 5, 2014 07:05
-
-
Save danlamanna/538e585ee1df4d8e28c6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#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