Given an M×N matrix, this program produces two independently sorted versions:
- Rows sorted ascending — within each row, elements are rearranged smallest to largest. Rows are independent of each other.
- Columns sorted descending — within each column, elements are rearranged largest to smallest (operating on the original matrix, not the row-sorted one). Columns are independent of each other.
The original used void main(), static int arrays (unnecessary — local arrays in main are fine), and broken \n. This rewrite refactors into helper functions for clarity.
Trace for a 3×3 Matrix
Input: [3,1,4; 1,5,9; 2,6,5]
| Row 0 | Row 1 | Row 2 | |
|---|---|---|---|
| Original | 3, 1, 4 | 1, 5, 9 | 2, 6, 5 |
| Rows sorted asc | 1, 3, 4 | 1, 5, 9 | 2, 5, 6 |
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Original (col values) | 3, 1, 2 | 1, 5, 6 | 4, 9, 5 |
| Columns sorted desc | 3, 2, 1 | 6, 5, 1 | 9, 5, 4 |
C Program: Sort Matrix Rows and Columns
/* Sort matrix rows in ascending order and columns in descending order
* Compile: gcc -ansi -Wall -Wextra matsort.c -o matsort */
#include <stdio.h>
#define MAX 10
void print_matrix(int a[][MAX], int r, int c)
{
int i, j;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++)
printf("%4d", a[i][j]);
printf("\n");
}
}
void sort_row_asc(int row[], int n)
{
int i, j, tmp, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++)
if (row[j] < row[min_idx]) min_idx = j;
tmp = row[i]; row[i] = row[min_idx]; row[min_idx] = tmp;
}
}
void sort_col_desc(int a[][MAX], int r, int col)
{
int i, k, tmp;
for (i = 0; i < r - 1; i++)
for (k = i + 1; k < r; k++)
if (a[i][col] < a[k][col]) {
tmp = a[i][col]; a[i][col] = a[k][col]; a[k][col] = tmp;
}
}
int main(void)
{
int row_sorted[MAX][MAX], col_sorted[MAX][MAX];
int i, j, m, n;
printf("Enter matrix order (rows cols): ");
if (scanf("%d %d", &m, &n) != 2 || m<1||m>MAX||n<1||n>MAX) {
printf("Invalid dimensions.\n"); return 1;
}
printf("Enter %dx%d elements:\n", m, n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (scanf("%d", &row_sorted[i][j]) != 1) {
printf("Invalid.\n"); return 1;
}
col_sorted[i][j] = row_sorted[i][j];
}
}
printf("\nOriginal matrix:\n");
print_matrix(row_sorted, m, n);
for (i = 0; i < m; i++)
sort_row_asc(row_sorted[i], n);
printf("\nRows sorted ascending:\n");
print_matrix(row_sorted, m, n);
for (j = 0; j < n; j++)
sort_col_desc(col_sorted, m, j);
printf("\nColumns sorted descending:\n");
print_matrix(col_sorted, m, n);
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra matsort.c -o matsort
./matsort
Sample Output
Enter matrix order (rows cols): 3 3 Enter 3x3 elements: 3 1 4 1 5 9 2 6 5 Original matrix: 3 1 4 1 5 9 2 6 5 Rows sorted ascending: 1 3 4 1 5 9 2 5 6 Columns sorted descending: 3 6 9 2 5 5 1 1 4
Code Explanation
- Two separate copies —
row_sortedandcol_sortedare both initialized from the input. Row sorting modifiesrow_sorted; column sorting modifiescol_sorted. They are independent operations on the original data. If you sorted columns of the already row-sorted matrix, you would get a third, different result. - sort_row_asc(row[], n) — takes a single 1D array (one row of the 2D matrix, passed as a pointer) and sorts it in place using selection sort. Passing
row_sorted[i]gives a pointer to the first element of row i, which decays to a regularint[]parameter. - sort_col_desc(a[][MAX], r, col) — operates on one column of the 2D array. Since 2D arrays are stored row-major, column elements are not contiguous in memory — they are at positions [0][col], [1][col], [2][col]…. You cannot sort a column with a 1D sort function without extracting it first. Operating on the column in-place via the 2D array is the standard approach.
- Why selection sort for rows? — selection sort is easy to understand and makes at most N-1 swaps. For the small matrix sizes typical of these exercises, its O(n²) time does not matter. For large matrices, prefer insertion sort (better cache behavior) or qsort() from stdlib.h.
What This Program Teaches
- Row-major storage — in C, a 2D array
int a[M][N]stores row 0 contiguously, then row 1, then row 2. Row access is cache-friendly; column access jumps by N ints between elements. This is whysort_row_asctakes a flat int[], butsort_col_descmust take the full 2D array and a column index. - Passing 2D arrays to functions — C requires all dimensions except the first to be specified in the parameter:
int a[][MAX]. This allows the compiler to compute the correct offset fora[i][j]asa + i*MAX + j. Omitting MAX would make the offset computation impossible. - Independent vs dependent transformations — sorting rows and columns are independent operations here because each uses a separate copy of the data. In practice, decide whether your operations should compose (chain) or be independent (parallel), and design data copies accordingly.
Related Programs
- Bubble Sort in C
- Selection Sort in C
- Sort Numbers Descending in C
- Swap Matrix Diagonals in C
- Matrix Addition, Subtraction and Trace in C
Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
|
C Programming: A Modern Approach — K.N. King (India) |
(US)
Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.