Sort the matrix
C program to sort the matrix.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void sort_array_ascending(int a[MAX*MAX], int n)
{
int i, j, temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void sort_matrix_ascending(int mat[MAX][MAX], int row, int col)
{
int i, j;
int temp[MAX*MAX];
int count;
count = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
temp[count] = mat[i][j];
count++;
}
}
sort_array_ascending(temp, count);
count = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
mat[i][j] = temp[count];
count++;
}
}
}
void sort_array_descending(int a[MAX*MAX], int n)
{
int i, j, temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void sort_matrix_descending(int mat[MAX][MAX], int row, int col)
{
int i, j;
int temp[MAX*MAX];
int count;
count = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
temp[count] = mat[i][j];
count++;
}
}
sort_array_descending(temp, count);
count = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
mat[i][j] = temp[count];
count++;
}
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
sort_matrix_ascending(mat, row, col);
printf("\nSorted Matrix in ascending order is\n");
print_matrix(mat, row, col);
sort_matrix_descending(mat, row, col);
printf("\nSorted Matrix in descending order is\n");
print_matrix(mat, row, col);
getch();
}
Output
Enter the number of rows :3
Enter the number of columns :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :4
Element [0][2] :3
Element [0][3] :5
Element [1][0] :7
Element [1][1] :54
Element [1][2] :56
Element [1][3] :78
Element [2][0] :98
Element [2][1] :54
Element [2][2] :3
Element [2][3] :34
Matrix entered is
1 4 3 5
7 54 56 78
98 54 3 34
Sorted Matrix in ascending order is
1 3 3 4
5 7 34 54
54 56 78 98
Sorted Matrix in descending order is
98 78 56 54
54 34 7 5
4 3 3 1