
编写代码,将矩阵的所有行按升序排序,所有列按降序排序。矩阵的大小和元素由用户在运行时提供。
下面解释了在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 </p><p>");
scanf ("%d %d", &m,&n);
printf ("Enter co-efficients of the matrix </p><p>");
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 </p><p>");
for (i=0;i<m;++i){
for (j=0;j<n;++j){
printf (" %d",ma[i][j]);
}
printf ("</p><p>");
}
printf ("After arranging rows in ascending order</p><p>");
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 ("</p><p>");
}
printf ("After arranging the columns in descending order </p><p>");
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 ("</p><p>");
}
}当上述程序被执行时,它产生以下结果 −
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
以上就是C程序对矩阵的所有列和行进行排序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号