Let's define a struct named "Edge".
#include <stdio.h>
#include <stdlib.h>
struct Edge{
int first;
int second;
float score;
};
struct Edge* newEdge(int first, int second, float score){
struct Edge* edge = (struct Edge*)malloc(sizeof(struct Edge*));
edge->first = first;
edge->second = second;
edge->score = score;
return edge;
}
Given an array of edges, each of which consists of two vertices and a score, I have to sort the edges in descending/ascending order of their scores. I've written a comparator function. The following is what I've tried. However, it doesn't produce the correct output.
int comparator_function(const void *v1, const void *v2){
struct Edge* e1 = (struct Edge*) v1;
struct Edge* e2 = (struct Edge*) v2;
if(e1->score < e2->score){
return 1;
}
return 0;
}
int main(){
struct Edge* edges[5];
edges[0] = newEdge(1, 2, 1.23);
edges[1] = newEdge(4, 3, 3.222);
edges[2] = newEdge(2, 2, 5.222);
edges[3] = newEdge(5, 1, 4.222);
edges[4] = newEdge(3, 4, 2.4);
for(int i=0;i<5;i++){
printf("%d, %d, %f\n", edges[i]->first, edges[i]->second, edges[i]->score);
}
printf("\n\n");
qsort(edges, 5, sizeof(struct Edge*), comparator_function);
for(int i=0;i<5;i++){
printf("%d, %d, %f\n", edges[i]->first, edges[i]->second, edges[i]->score);
}
return 0;
}
The output of the quicksort I'm getting is -
4, 3, 3.222000
5, 1, 4.222000
2, 2, 5.222000
1, 2, 1.230000
3, 4, 2.400000
I'm not sure if my compare function is right or not. Any help would be appreciated.