C program to sort all columns and rows of matrix


Problem

Write a code to sort all the rows of matrix in an ascending order and all columns in the descending order. The size of matrix and elements of matrix are given by user at runtime.

Solution

The solution to sort all the rows of matrix in an ascending order and all columns in the descending order in the C programming language is explained below −

The logic used to sort the rows in an ascending order is as follows

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;
         }
      }
   }
}

The logic used to sort the columns in the descending order is as follows −

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;
         }
      }
   }
}

Program

Following is the C program to sort all the rows of matrix in an ascending order and all columns in the descending order

 Live Demo

#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 ("
");    } }

Output

When the above program is executed, it produces the following result −

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

Updated on: 01-Sep-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements