首页  >  文章  >  后端开发  >  C程序对矩阵的所有列和行进行排序

C程序对矩阵的所有列和行进行排序

王林
王林转载
2023-09-14 09:17:021218浏览

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 </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中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除