The Program in C to sort all the elements of a matrix is given below:
#include <stdio.h>
#include <stdlib.h>
void sort_matrix(int *matrix, int rows, int cols) {
int temp;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
for (int x = i; x < rows; x++) {
for (int y = (x==i) ? j+1 : 0; y < cols; y++) {
if (matrix[x*cols+y] < matrix[i*cols+j]) {
temp = matrix[i*cols+j];
matrix[i*cols+j] = matrix[x*cols+y];
matrix[x*cols+y] = temp;
}
}
}
}
}
}
int main() {
int rows, cols, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
printf("Enter the elements of the matrix: \n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
sort_matrix((int*)matrix, rows, cols);
printf("Sorted matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of the matrix:
12
66
45
32
Sorted matrix:
12 32
45 66
Pro-Tips💡
This program prompts the user to enter the number of rows and columns of the matrix, and then the elements of the matrix.
It then uses the sort_matrix function to sort all elements of the matrix in ascending order by using nested loops and the bubble sort algorithm.
You can call this function by passing the matrix, rows and cols as arguments
sort_matrix((int*)matrix, rows, cols);
It is important to note that, this program uses 2-D array to store a matrix and the memory is allocated in a continuous block of memory in a row-major order.
The bubble sort algorithm has a time complexity of O(n^2) so it is not efficient for large matrices.
If you need to sort large matrices you should use a sorting algorithm with better performance like quicksort or merge sort.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.