按字符串对结构数组进行排序

Sort array of structs by string

我有这样的结构:

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;

我正在尝试使用此函数按 cName 对该结构的数组进行排序:

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);
}

其中 iCantAgentes 是数组中代理的数量,agentesArr 是数组。 由于某种原因,它不起作用。有人可以帮我找出问题吗?

您的函数只对相邻的字符串进行排序,而不是对整个数组进行排序。试试这个:

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;
            }
        }
    }
}