Open In App

C Program To Sort 2D Array Across Rows

Last Updated : 02 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to sort 2D array row-wise
#include <stdio.h>
  
// This function sort 2D array row-wise
void sortRowWise(int m[][4], int r, int c)
{
    int t = 0;
    
    // loop for rows of 2d array
    for (int i = 0; i < r; i++) {
        
        // loop for column of 2d array
        for (int j = 0; j < c; j++) {
            
            // loop for comparison and swapping the elements
            for (int k = 0; k < c - j - 1; k++) {
                
                if (m[i][k] > m[i][k + 1]) {
                    
                    // swap the elements
                    t = m[i][k];
                    m[i][k] = m[i][k + 1];
                    m[i][k + 1] = t;
                }
            }
        }
    }
  
    // print the sorted matrix
    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");
    }
}
  
// Driver code
int main()
{
    // Input Array
    int arr[][4] = { { 8, 5, 7, 2 },
                     { 7, 3, 0, 1 },
                     { 8, 5, 3, 2 },
                     { 9, 4, 2, 1 } };
  
    // print input array
    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) accepts 2D-array, no of rows
    // and columns as input and print a row-wise sorted 2D
    // array
    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).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads