c - what happened when using qsort function? -


i'm trying sort struct node variable a, result turns out wrong.

my result:

{5, 4},  {6, 2},  {7, 3},  {4, 1},  {3, 7},  {1, 3},  {0, 0}, 

my code:

#include <stdio.h> #include <stdlib.h>  typedef struct node {     int x;     int y; } n;  int num = 7;  int compare(const void *ele1, const void *ele2) {     n *px, *py;     px = (n *) ele1;     py = (n *) ele2;     return px->x < py->x; }  int main() {     n node[7] = {     {4, 1},     {6, 2},     {1, 3},     {5, 4},     {7, 3},     {3, 7}     };     int i;     qsort(node, num, sizeof (node[0]), compare);     (i = 0; < num; i++)         printf("{%d, %d},  ", node[i].x, node[i].y);     return 0; } 

if sort 6 pairs of elements, result is:

{7, 3},  {6, 2},  {5, 4},  {4, 1},  {1, 3},  {0, 0}, 

which correct, when tried seven, shows results above. know why happens? thanks!

the result of comparison function should return negative number, 0, or positive number. returning 0 or 1.

your comparison function should return this:

return px->x < py->x ? -1 : px->x == py->x ? 0 : 1; 

or terser little more opaque:

return px->x - py->x; 

see qsort reference. it's technically c++ reference page, explanation c well.

addendum

i forgot explain happened, sorry! comparison function following.

  • whenever px->x < py->x, function returned 1, making think px tuple greater py tuple, when in fact not. (you wanted return negative value in case.)

  • whenever px->x >= py->x, function returned 0, making qsort think 2 values equal, when in fact may or may not have been.

so qsort blindly partitioning , swapping elements according comparison function telling order was. function giving "equal" (0) or "greater" (1), , never "less", final result turned out rather scrambled.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -