Write a c program to sort elements in row wise and print the elements of matrix in Column major order
#include <stdio.h>
#include <stdlib.h>
// Function to sort a row in ascending order
void sortRowAscending(int *row, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (row[i] > row[j]) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
}
}
}
}
int main() {
int m, n;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
int matrix[m][n];
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Sort each row in ascending order
for (int i = 0; i < m; i++) {
sortRowAscending(matrix[i], n);
}
printf("Matrix elements in column major order:\n");
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Comments
Post a Comment