SR> I am trying to sort a struct but it needs to be sorted by
SR> AKA. It sorts the list to a degree but I end up with
SR> 1:xxx/xxx
SR> 111:xxx/xxx
SR> 2:xxx/xxx
SR> Anyone got a simple solution to this.
See if this offers any solutions. It assumes a Borland
compiler for cursor control, but you can just lose the
gotoxy() and use printf() to display the data.
/* ----- strctsrt.c begins ----- */
#include
#include
#include
#include
#include
typedef struct {
char name[13];
int id;
} NAMES;
int compA( const void *a, const void *b)
{
return strcmp(((NAMES*)a)->name, ((NAMES*)b)->name);
/* Multiple dereferences not necessary.
** You have a void pointer.
** You WANT a struct pointer.
** A simple cast to type will do.
*/
}
int compB(const void *a, const void *b)
{
int iA = ((NAMES*)a)->id, iB = ((NAMES*)b)->id;
if(iA > iB) return 1;
if(iA < iB) return -1;
return 0;
}
/* Since multiple references are required for the multiple
** comparisons, it is more efficient to use a single point
** of dereference and employ variables of the proper type
** for the actual comparisons.
** (const void*, const void*) required for qsort() functions.
** The prototype is in the stdlib.h file and the function
** prototype must match that found in stdlib.h
*/
void name_out(int y, int x, NAMES n)
{
gotoxy(y, x);
cprintf("%s --- ID %02d\n", n.name, n.id);
}
NAMES *name_make(NAMES *n)
{
sprintf(n->name, "%cname", (char)('A' + rand() % 26));
n->id = rand();
return n;
}
int main (void)
{
int i;
NAMES name[20];
srand((unsigned)time(NULL));
clrscr();
printf("Original :\t\tSorted by ID : \t\t Sorted by Name :\n");
for(i = 0; i < 20;i++)
name_out(3, i + 2, *name_make(&name[i]));
/* random fill structs
** Since name_make() wants (NAMES*), we send the address.
** Since name_out() wants NAMES, we dereference the pointer
** returned by name_make() to satisfy it.
*/
getch();
qsort((void*)name, 20, sizeof(NAMES), compB);
for(i = 0; i < 20;i++)
name_out(27, i + 2, name[i]);
getch();
qsort((void*)name, 20, sizeof(name[0]), compA);
/* Note:
** results of previous sort nullified in secondary sort
** when using the qsort() function. Array will not be
** sorted by ID no. within groups where the name field
** is identical.
*/
for(i = 0; i < 20;i++)
name_out(52, i + 2, name[i]);
getch();
return 0;
}
/* ----- strctsrt.c ends ----- */
> ] Facts are unnecessary encumberance to Truth - Joan D'Arc..
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)
|