C Program to sort rows of the Matrix
Last Updated :
10 Jan, 2022
Given a matrix arr[][] of dimensions N * M, the task is to sort the matrix such that each row is sorted and the first element of each row is greater than or equal to the last element of the previous row.
Examples:
Input: N = 3, M = 3, arr[][] = {{7, 8, 9}, {5, 6, 4}, {3, 1, 2}}
Output:
1 2 3
4 5 6
7 8 9
Approach: Follow the steps below to solve the problem:
- Traverse the matrix
- For every matrix element, consider it to be the minimum element in the matrix. Check if there is a smaller element present in the rest of the matrix.
- If found to be true, swap the current element and the minimum element in the matrix.
- Finally, print the sorted matrix.
Below is the implementation for the above approach:
C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void sort_matrix( int arr[SIZE][SIZE],
int N, int M)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
int minimum = arr[i][j];
int z = i;
int q = j;
int w = j;
for ( int k = i; k < N; k++) {
for (; w < M; w++) {
if (arr[k][w] < minimum) {
minimum = arr[k][w];
z = k;
q = w;
}
}
w = 0;
}
int temp = arr[i][j];
arr[i][j] = arr[z][q];
arr[z][q] = temp;
}
}
}
void printMat( int arr[SIZE][SIZE],
int N, int M)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
printf ( "%d " , arr[i][j]);
}
printf ( "\n" );
}
}
int main()
{
int N = 3, M = 3;
int arr[SIZE][SIZE]
= { { 7, 8, 9 },
{ 5, 6, 4 },
{ 3, 1, 2 } };
sort_matrix(arr, N, M);
printMat(arr, N, M);
return 0;
}
|
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(N4)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...