C Program To Sort 2D Array Across Rows
Last Updated :
02 Aug, 2022
Here, we will see how to sort the 2D Array across rows using a C program:
Input:
8 5 7 2
7 3 0 1
8 5 3 2
9 4 2 1
Output:
2 5 7 8
0 1 3 7
2 3 5 8
1 2 4 9
Approach:
In this approach, we use Bubble Sort. First Start iterating through each row of the given 2D array, and sort elements of each row using the Bubble sort sorting algorithm.
Below is the implementation of the above approach:
C
#include <stdio.h>
void sortRowWise( int m[][4], int r, int c)
{
int t = 0;
for ( int i = 0; i < r; i++) {
for ( int j = 0; j < c; j++) {
for ( int k = 0; k < c - j - 1; k++) {
if (m[i][k] > m[i][k + 1]) {
t = m[i][k];
m[i][k] = m[i][k + 1];
m[i][k + 1] = t;
}
}
}
}
printf ( "\n Row-Wise Sorted 2D Array \n" );
for ( int i = 0; i < r; i++) {
for ( int j = 0; j < c; j++)
printf ( " %d" , m[i][j]);
printf ( "\n" );
}
}
int main()
{
int arr[][4] = { { 8, 5, 7, 2 },
{ 7, 3, 0, 1 },
{ 8, 5, 3, 2 },
{ 9, 4, 2, 1 } };
printf ( "\n Input Array \n" );
for ( int i = 0; i < 4; i++) {
for ( int j = 0; j < 4; j++) {
printf ( " %d" , arr[i][j]);
}
printf ( "\n" );
}
sortRowWise(arr, 4, 4);
return 0;
}
|
Output
Input Array
8 5 7 2
7 3 0 1
8 5 3 2
9 4 2 1
Row-Wise Sorted 2D Array
2 5 7 8
0 1 3 7
2 3 5 8
1 2 4 9
Time Complexity: O(r*c*max(r,c)).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...