C语言程序用于对矩阵的所有行和列进行排序
问题
编写代码以将矩阵的所有行按升序排序,并将所有列按降序排序。矩阵的大小和矩阵元素由用户在运行时给出。
解决方案
以下是使用 C 编程语言对矩阵的所有行进行升序排序以及对所有列进行降序排序的解决方案:
用于按升序排序行的逻辑如下:
for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } }
用于按降序排序列的逻辑如下:
for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } }
程序
以下是 C 程序,用于将矩阵的所有行按升序排序,并将所有列按降序排序:
#include <stdio.h> void main(){ int i,j,k,a,m,n; static int ma[10][10],mb[10][10]; printf ("Enter the order of the matrix
"); scanf ("%d %d", &m,&n); printf ("Enter co-efficients of the matrix
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ scanf ("%d",&ma[i][j]); mb[i][j] = ma[i][j]; } } printf ("The given matrix is
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("
"); } printf ("After arranging rows in ascending order
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("
"); } printf ("After arranging the columns in descending order
"); for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",mb[i][j]); } printf ("
"); } }
输出
执行上述程序时,将产生以下结果:
Enter the order of the matrix 3 4 Enter co-efficient of the matrix 1 2 3 4 1 2 3 4 5 1 2 3 The given matrix is 1 2 3 4 1 2 3 4 5 1 2 3 After arranging rows in ascending order 1 2 3 4 1 2 3 4 1 2 3 5 After arranging the columns in descending order 5 2 3 4 1 2 3 4 1 1 2 3
广告