user300045
user300045

Reputation: 259

Sorting specific elements in structure

I have a question about sorting elements in structure. If I have two structures:

typedef struct
{
    char name[25],surname[25];
    int number;
}PLAYER;

typedef struct
{
    char nameofteam[25];
    int numberofplayers;
    PLAYER *players;
}TEAM;

How to sort data about players in a team by ascending order of the numbers on the jersey (int number)? Prototype of function is void sort(TEAM *).

This gives an error .exe has stopped working:

void sort(TEAM *p)
{

    int i,j;
    for(i=0;i<p->numberofplayers-1;i++)
    for(j=i+1;j<p->numberofplayers;j++)
    if((p[i].players)->number > (p[j].players)->number)
    {
        TEAM temp=p[i];
        p[i]=p[j];
        p[j]=temp;
    }
}

The problem is that number on jersey (int number) isn't in structure TEAM.

When specific element for sorting is in structure, then the checking would go like this:

if(p[i].element > p[j].element)

Should I use dynamic allocation for *players in this function?

Thanks for the answers.

Upvotes: 0

Views: 75

Answers (1)

WhozCraig
WhozCraig

Reputation: 66234

Your code logic is indexing off p, which is the team base pointer, not the players base pointer within the team. Everywhere you see this:

p[i]

should be this:

p->players[i]

Once that is addressed, the proper swap temp is required as well, which should be a PLAYER, not a TEAM

Something like this:

void sort(TEAM *p)
{
    int i,j;
    for(i=0; i<p->numberofplayers-1; ++i)
    {
        for(j=i+1; j<p->numberofplayers; ++j)
        {
            if(p->players[i].number > p->players[j].number)
            {
                PLAYER tmp = p->players[i];
                p->players[i] = p->players[j];
                p->players[j] = tmp;
            }
        }
    }
}

All of this assuming you properly allocated the players member of the team, and numberofplayers accurately reflects that allocation.

Best of luck.

Upvotes: 1

Related Questions