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.
这个排序有很多问题。我正在尝试按名称排序,但strcmp的表现并不像我认为的那样。 TextArt只是一个结构数组,我确保正确存储值。所以我认为问题在于我如何将值传递给strcmp。无论哪种方式,字符串都没有正确排序。当我从strcmp获得返回值时,它们只是正值,我知道不应该是这种情况。
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;
}
}
}
1 个解决方案
#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:
你有Jonathan提到的问题,但真正阻止它工作的问题是测试条件是错误的字符串和错误的条件。正确的测试是:
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.
请注意,比较在pos_min和j之间,j现在用于第一个参数。
#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:
你有Jonathan提到的问题,但真正阻止它工作的问题是测试条件是错误的字符串和错误的条件。正确的测试是:
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.
请注意,比较在pos_min和j之间,j现在用于第一个参数。