c - C 中的矩阵排序

标签 c sorting matrix columnsorting

我有一个如下所示的矩阵

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/

相关文章:

c - 从c中的stdin读取字符串

将具有十六进制值的字符转换为字符串

python - 将 2-d 矩阵的每一列乘以 3-d 矩阵的每个切片的更有效方法

Matlab:向量矩阵的行列式

java - C 函数指针未在 Android Studio 中编译 : Gives Error "Can' t resolve type F"

C 代码不会在 mac 终端中编译。

c++ - BinarySearch 返回它所属位置的索引

Java写入文件排序数组

c++ - Intel TBB 使用task_group 进行双调排序

c - 矩阵幂和指针