سؤال

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;
        }
    }
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top