0
struct Edge
{
    int src, dest, weight;
}; typedef struct Edge Edge;

struct Graph
{
    int V, E;
    Edge* edge;
}; typedef struct Graph Graph;

I have a graph struct like this. I am trying to use qsort to sort all the edges in increasing order of their weight. in main:

Graph* graph = (Graph*)malloc(sizeof(Graph));
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);

Mycomp function:

    int myComp(const void* a, const void* b)
{
    Edge* a1 = (Edge*)a;
    Edge* b1 = (Edge*)b;
    return a1->weight > b1->weight;
}

After all, I tried to print every edge before and after the qsort, the order has been changed but it is not the correct order. Anyone can help with these? What part is wrong in my code?

alk
  • 69,737
  • 10
  • 105
  • 255

2 Answers2

2
return a1->weight > b1->weight;

should be

return a1->weight - b1->weight;

From the manual:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

Nothing to add to the answer by @n.m.

However you can compactify your declarations a bit if you write

typedef struct Edge
{
    int src, dest, weight;
} Edge;

or even

typedef struct
{
    int src, dest, weight;
} Edge;

if you plan to use a type-def'd name Edge only and will not need an explicit name of the basic type struct Edge.

CiaPan
  • 9,381
  • 2
  • 21
  • 35