简体   繁体   中英

Sort array of structs by string

I have this structure:

struct agente {
    int iCode;
    char cName[21];
    char cLName[21];
    char cAgentID[16];
    char cAssets[5][35];
    int iContAssets;
    int iAge;
    char cGender;
    char cMission[5][13];
    int iContMisiones;
};

typedef struct agente agente;

and I'm trying to sort an array of that structure by cName, using this function:

void sortAgents(agente* agentesArr, int iCantAgentes) {
    int didSwap = 0;
    agente temp;

    do {
        didSwap = 0;
        for(int i = 0; i < iCantAgentes - 1; i++) {
            int comp = strcmp(agentesArr[i].cName, agentesArr[i+1].cName);
            if(comp > 0 ) {
                temp = agentesArr[i];
                agentesArr[i] = agentesArr[i+1];
                agentesArr[i+1] = temp;
                didSwap = 1;
            }
        }
    } while(didSwap == 1);
}

where iCantAgentes is amount of agents on the array, and agentesArr is the array. For some reason, it's not working. Can someone help me identify the problem please?

Your function only sorts adjacent strings, not the whole array. Try this:

void sortAgents(agente* agentesArr, int iCantAgentes) {
    agente temp;

    for(int i = 0; i < iCantAgentes - 1; i++) {
        for(int j=i+1; j < iCantAgentes - 1; j++){
            int comp = strcmp(agentesArr[i].cName, agentesArr[j].cName);
            if(comp > 0) {
                temp = agentesArr[i];
                agentesArr[i] = agentesArr[j];
                agentesArr[j] = temp;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM