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 \n");
scanf ("%d %d", &m,&n);
printf ("Enter co-efficients of the matrix \n");
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 \n");
for (i=0;i<m;++i){
for (j=0;j<n;++j){
printf (" %d",ma[i][j]);
}
printf ("\n");
}
printf ("After arranging rows in ascending order\n");
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 ("\n");
}
printf ("After arranging the columns in descending order \n");
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 ("\n");
}
}
执行上述程序时,会产生以下结果 -
Enter the order of the matrix3 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
以上是 C程序对矩阵的所有列和行进行排序 的全部内容, 来源链接: utcz.com/z/341335.html