我正在对像这样的2D数组进行气泡排序。我对如何将我的最大值设为1并使第二行的值跟在第一行的对应值上感到困惑。
Input:
13 9 1 8 5
1 2 3 4 1
Actual output:
1 5 8 9 13
1 2 3 4 1
这是我想要的预期输出。
Output:
5 8 9 13 1
1 4 2 1 1
这是我对卡片进行排序的代码(col = 5,row = 2):
void sortedCards(int card[][col])
{
int i, j, k, temp;
printf("\n\nSorted Cards\n");
for (k = 0; k < 10; k++)
{
for (i = 0; i < row - 1; i++)
{
for (j = 0; j < col - 1; j++)
{
if (card[i][j] > card[i][j + 1])
{
temp = card[i][j];
card[i][j] = card[i][j + 1];
card[i][j + 1] = temp;
}
}
}
}
for (i = 0; i < row; i++)
{
if (i == 1)
{
printf("\n");
}
for (j = 0; j < col; j++)
{
printf("%i ", card[i][j]);
}
}
}
答案 0 :(得分:1)
如果排序仅取决于第一行,则无需遍历第二行。只需在检查第一行的同时设置两行即可。 另外,如果希望将1视为比所有其他数字都大,则需要将其添加到布尔逻辑中。如下调整您的for循环即可。
int j, k, temp, temp2;
for (k = 0; k < 10; k++)
{
for (j = 0; j < col-1; j++)
{
//here we only test row 0, and we check if the value is 1
if (card[0][j] == 1 || (card[0][j] > card[0][j+1] && card[0][j+1] != 1))
{
//all other reassignment is the same but you do both rows at the same time
temp = card[0][j];
temp2 = card[1][j];
card[0][j] = card[0][j + 1];
card[1][j] = card[1][j + 1];
card[0][j + 1] = temp;
card[1][j + 1] = temp2;
}
}
}