Sort Char vector in C using selection method

Asked

Viewed 2,935 times

1

I am trying to sort a char vector using the selection method (Seletion Sort), but it is returning me the vector exactly the same way, without even making a change. Can someone point me to the error in the code?

void selectionSortChar(char v[][30], int max) {
    int i, j, min;
    char aux[30];

    for (i = 0; i < (max - 1); i++) {
        min = i;
        for (j = i + 1; j < max; j++) {
            if (stricmp(v[j], v[j + 1]) > 0) {
                min = j;
            }
        }
        if (i != min) {
            strcpy(aux, v[j]);
            strcpy(v[j], v[j + 1]);
            strcpy(v[j + 1], aux);
        }
    }
    mostraVetorChar(v, 6);
}
  • 1

    I didn’t test it, I don’t know where the mistake is, but looking real quick, the last if shouldn’t be min instead of j no?

1 answer

3


Along those lines:

if (stricmp(v[j], v[j + 1]) > 0) {

Are you comparing j with j + 1, and not with min. Even this can cause a segfault, for j + 1 may equal to max! (assuming that max is the exclusive limit)

Assuming you intend to order in descending order (otherwise, just reverse the comparison of > for <), replace this problematic line with:

if (strcmp(v[min], v[j]) > 0) {

And I believe that everything will work properly. If max is a limit inclusive, it is also necessary to change the conditions of both fors to <=.

Updating: in accordance with pointed out by Felipe Avelar in the comments, within the latter if you are also exchanging j with j + 1, and not i with min. Change that last one if for:

if (i != min) {
    strcpy(aux, v[i]);
    strcpy(v[i], v[min]);
    strcpy(v[min], aux);
}
  • mgibsonbr, ba had not seen this, very silly mistake. Thanks for the clarification!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.