我有一个如下所示的矩阵
Col1 Col2 Col3
5 10 3
2 4 0
7 14 0
2 6 1
1 2 1
4 8 2
6 12 3
我想根据 Col2 对矩阵进行升序排序。矩阵应该看起来像
Col1 Col2 Col3
1 2 1
2 4 0
2 6 1
4 8 2
5 10 3
6 12 3
7 14 0
我不确定 C 中可用的方法如何执行此操作。 非常感谢任何帮助
最佳答案
#include <stdio.h>
#include <stdlib.h>
#define COL_SIZE 3
int cmp(const void *a, const void *b){
#if 0
int (*x)[COL_SIZE] = (int(*)[COL_SIZE])a;
int (*y)[COL_SIZE] = (int(*)[COL_SIZE])b;
int col2_0 = x[0][1];
int col2_1 = y[0][1];
#endif
int col2_0 = ((int *)a)[1];
int col2_1 = ((int *)b)[1];
return (col2_0 > col2_1) - (col2_0 < col2_1);
}
int main(void) {
int matrix[][COL_SIZE] = {
{5, 10, 3},
{2, 4, 0},
{7, 14, 0},
{2, 6, 1},
{1, 2, 1},
{4, 8, 2},
{6, 12, 3}
};
size_t sizeof_row = sizeof(*matrix);
size_t num_of_row = sizeof(matrix) / sizeof_row;
qsort(matrix, num_of_row, sizeof_row, cmp);
for(int r = 0; r < num_of_row; ++r){
for(int c = 0; c < COL_SIZE; ++c){
printf("%2d ", matrix[r][c]);
}
puts("");
}
return 0;
}
关于c - C 中的矩阵排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33359323/