0

Having a number of problems with this sorting. I'm trying to sort by name, but strcmp is not behaving the way that I believed it to. TextArt is just an array of structs, I made sure the values are properly stored. So I believe the problem lies with how I am passing the values to strcmp. Either way, the strings are not being sorted properly. When I get the return value from strcmp, they are only positive values, and I know that should not be the case.

void selectionSort(TextArt *asciiArt, int size)
{
    //pos_min is short for position of min
    int pos_min;
    TextArt temp;
    int i=0;
    int j=0;

    for (i=0; i < size-1; i++)
    { printf("loop %i", i);
        pos_min = i;//set pos_min to the current index of array

        for (j = i + 1; j < size; j++)
        {
            if ((strcmp((asciiArt+i)->artistName, (asciiArt+j)->artistName)) < 0 &&
                (strcmp((asciiArt+i)->artistName, (asciiArt+j)->artistName)) != 0)
            {
                printf("pos min is %i", pos_min);
                pos_min = j; //pos_min will keep track of the index that min is in, this is needed when a swap happens
            }
        }
        if (pos_min != i)
        {
            printf("copying...\n");
            const TextArt temp = *(asciiArt + pos_min);
            *(asciiArt + pos_min) = *(asciiArt + i);
            *(asciiArt + i) = temp;
        }
    }
}
2
  • See Selection sort in C using an array of struct -- error lvalue required for the data structures. Please copy the structure definition into this question. Commented Apr 19, 2014 at 0:29
  • 4
    You don't need both strcmp() operations; the first is probably sufficient. You are effectively comparing a[i] < a[j] && a[i] != a[j] and you don't need the second test when the first is true. The printing of pos_min is arguably either in the wrong place (should be after the assignment) or inaccurately described (should be 'was' instead of 'is'). Commented Apr 19, 2014 at 0:31

1 Answer 1

1

You have the problems that Jonathan mentions but the problems that really keep this from working are that the test condition is for the wrong strings and the wrong condition. The correct test is:

if (strcmp((asciiArt+j)->artistName, (asciiArt+pos_min)->artistName) < 0)

Note that the comparison is between pos_min and j and that j is now used for the first argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.