Sorting a struct
Author Message
Sorting a struct

Quote:

>    How do you use Qsort to sort a struct?  My strcut is set up like
>the following:
>struct
>  {
>  int x_pos;
>  int y_pos;
>  int picture;
>  int layernum;
>  } map_info[1001];  /* 1001 is the maximium...300-500 is the norm*/
>    I don't use Qsort that often, and I have never used it with a
>struct, so be gentle :)...no seriously, could anyone explain what each
>major command of the qsort function that would accomplish the task of
>sorting the x,y positions so that the x are sorted from lowest to highest as
>well as the y position?

Well, I'm afraid no sorting algorithm can accomplish what you want. If
you can live with the following: The array is sorted using x_pos as a key,
and using y_pos as a secondary key to break ties on x_pos, try something
like this:

a) Give the struct a name:

typedef struct tagMAPITEM
{
int x_pos;
int y_pos;

Quote:
} MAPITEM;

b) Define a function to compare to MAPITEMs

int mapcmp( const void *pa, const void *pb )
{
const MAPITEM *a = pa;
const MAPITEM *b = pb;
int cmp;

cmp = a->x_pos - b->x_pos;
if ( !cmp )
cmp = a->y_pos - b->y_pos;
return cmp;

Quote:
}

c) Define your array of MAPITEMs

MAPITEM map_info[ MAX_MAP_SIZE ];

d) Use qsort to sort the used part of the array

{
unsigned current_map_size;

qsort( map_info, current_map_size, sizeof map_info[ 0 ], mapcmp );

Quote:
}

--
| Kurt Watzka                             Phone : +49-89-2180-2158

Fri, 21 Feb 1997 17:14:05 GMT
Sorting a struct
How do you use Qsort to sort a struct?  My strcut is set up like
the following:

struct
{
int x_pos;
int y_pos;
int picture;
int layernum;
} map_info[1001];  /* 1001 is the maximium...300-500 is the norm*/

I don't use Qsort that often, and I have never used it with a
struct, so be gentle :)...no seriously, could anyone explain what each
major command of the qsort function that would accomplish the task of
sorting the x,y positions so that the x are sorted from lowest to highest as
well as the y position?
BTW I posted a similar question like this, and recieved many good
answers, but many of them said to use Qsort to sort the coordinates, and
I don't understand it that well. :)
____
|C:\>|                       _____________________
|____|                //~\  | Greg McLearn        |
_|__|_      ______/P//_  |\/|                     |

|______|~~~~ -----------     \---------------------

Fri, 21 Feb 1997 11:37:41 GMT

 Page 1 of 1 [ 2 post ]

Relevant Pages