此排序存在许多问题。我试图按名称排序,但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;
}
}
}
答案 0 :(得分:1)
你有Jonathan提到的问题,但真正阻止这种问题的问题是测试条件是错误的字符串和错误的条件。正确的测试是:
if (strcmp((asciiArt+j)->artistName, (asciiArt+pos_min)->artistName) < 0)
请注意,比较在pos_min和j之间,j现在用于第一个参数。