Sort vector of Char in C using selection method

1

I'm trying to sort a vector of char using the selection method (Seletion Sort), but it's returning the vector exactly the same, without even making a change. Can someone point me to where the error is 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);
}
    
asked by anonymous 20.03.2015 / 01:37

1 answer

3

On this line:

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

You are comparing j to j + 1 , not min . This can even cause a segfault , since j + 1 can be equal to max ! (assuming that max is the exclusive limit)

Assuming you want to sort in descending order (otherwise, just reverse the comparison of > to < ), replace that problematic line with:

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

And I believe that everything will work correctly. If max is an inclusive limit, you must also change the conditions of both for s to <= .

Update: as #, within the last if you are also permuting j with j + 1 , and not i %. min with if . Change this last %code% to:

if (i != min) {
    strcpy(aux, v[i]);
    strcpy(v[i], v[min]);
    strcpy(v[min], aux);
}
    
20.03.2015 / 01:44