我试图根据最后一列的值以降序对2d数组排序。我的代码如下:
#include <stdio.h>
#define totrow 10
#define totcolumn 6
float grade[totrow][totcolumn];
void reArg (float grade[][totcolumn]);
void reArg (float grade[][totcolumn])
{
int temp, x, k = 5;
for (int r = 0; r < totrow; r++)
{
for (int c = 0; c <totcolumn;c++)
{
if (grade[r][k] > grade[c][k])
{
for(x = 0; x < totcolumn;x++)
{
temp = grade[r][x];
grade[r][x]=grade[c][x];
grade[c][x]=temp;
}
}
}
}
for (int r = 0; r < totrow; r++)
{
for (int c = 0; c < totcolumn; c++)
{
printf("%.2f\t",grade[r][c]);
}
printf("\n");
}
}
代码编译后,我得到了我的数组:
7899.00 92.00 90.00 88.00 86.00 89.00
6814.00 85.00 86.00 92.00 88.00 87.00
8234.00 77.00 87.00 84.00 98.00 86.00
7654.00 76.00 87.00 84.00 88.00 83.00
3534.00 86.00 81.00 84.00 73.00 81.00
7284.00 56.00 81.00 87.00 98.00 80.00
9901.00 45.00 78.00 79.00 80.00 70.00
6465.00 87.00 54.00 68.00 72.00 70.00
7934.00 76.00 91.00 84.00 65.00 79.00
7234.00 76.00 81.00 84.00 78.00 79.00
原始数组为:
6814.00 85.00 86.00 92.00 88.00 87.75
7234.00 76.00 81.00 84.00 78.00 79.75
6465.00 87.00 54.00 68.00 72.00 70.25
7899.00 92.00 90.00 88.00 86.00 89.00
9901.00 45.00 78.00 79.00 80.00 70.50
8234.00 77.00 87.00 84.00 98.00 86.50
7934.00 76.00 91.00 84.00 65.00 79.00
7284.00 56.00 81.00 87.00 98.00 80.50
7654.00 76.00 87.00 84.00 88.00 83.75
3534.00 86.00 81.00 84.00 73.00 81.00
为什么程序只对前6行排序?
答案 0 :(得分:2)
问题是您使用的是for(int c = 0; c < totcolumn; c++)
,但是,正如我认为您试图制作一个Bubble Sort一样,您需要遍历两次行,例如:for(int c = 0; c < totrow; c++)
我创建了一个在本地运行的示例。
#include <stdio.h>
#define totrow 4
#define totcolumn 2
void reArg (float grade[][totcolumn]) {
int temp, x, k = 5;
for (int r = 0; r < totrow; r++) {
for (int c = 0; c < totrow; c++) {
if (grade[r][k] > grade[c][k]) {
for(x = 0; x < totcolumn ; x++) {
temp = grade[r][x];
grade[r][x]=grade[c][x];
grade[c][x]=temp;
}
}
}
}
for (int r = 0; r < totrow; r++) {
for (int c = 0; c < totcolumn; c++) {
printf("%.2f\t",grade[r][c]);
}
printf("\n");
}
}
int main() {
float grade[totrow][totcolumn] = {{1,2},{3,4},{0,0}};
reArg(grade);
return 0;
}