Open In App

C++ Program For Row Wise Sorting in 2D Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array, sort each row of this array and print the result.
Examples: 

Input:
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output:
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44

Input:
8 6 4 5
3 5 2 1
9 7 4 2
7 8 9 5
Output:
4 5 6 8
1 2 3 5
2 4 7 9
5 7 8 9

Method 1 (Using Bubble Sort): 
Start iterating through each row of the given 2D array, and sort elements of each row using an efficient sorting algorithm. 
 

C++




// C++ program to sort
// 2D matrix row-wise
#include<bits/stdc++.h>
using namespace std;
 
void sortRowWise(int m[][4],
                 int r, int c)
{
  // Loop for rows of matrix
  for (int i = 0; i < r; i++)
  {
    // Loop for column of matrix
    for (int j = 0; j < c; j++)
    {
      // Loop for comparison and swapping
      for (int k = 0; k < c - j - 1; k++)
      {
        if (m[i][k] > m[i][k + 1])
        {
          // Swapping of elements
          swap(m[i][k], m[i][k + 1]);
        }
      }
    }
  }
 
  // Printing the sorted matrix
  for (int i = 0; i < r; i++)
  {
    for (int j = 0; j < c; j++)
      cout << m[i][j] << " ";
    cout << endl;
  }
}
 
// Driver code
int main()
{
  int m[][4] = {{9, 8, 7, 1},
                {7, 3, 0, 2},
                {9, 5, 3, 2},
                {6, 3, 1, 2}};
  int c = sizeof(m[0]) / sizeof(m[0][0]);
  int r = sizeof(m) / sizeof(m[0]);
  sortRowWise(m, r, c);
  return 0;
}


Output

1 7 8 9 
0 2 3 7 
2 3 5 9 
1 2 3 6 

Time complexity: O(r*c*c).
Auxiliary Space: O(1) 

Method 2 (Using Library Function): 
The idea is to use Arrays.sort() for every row of the matrix.

C++




// C++ program to sort 2D
// matrix row-wise
#include <bits/stdc++.h>
using namespace std;
#define M 4
#define N 4
 
int sortRowWise(int m[M][N])
{
  // One by one sort
  // individual rows.
  for (int i = 0; i < M; i++)
    sort(m[i], m[i] + N);
 
  // Printing the sorted matrix
  for (int i = 0; i < M; i++)
  {
    for (int j = 0; j < N; j++)
      cout << (m[i][j]) << " ";
    cout << endl;
  }
}
 
// Driver code
int main()
{
  int m[M][N] = {{9, 8, 7, 1},
                 {7, 3, 0, 2},
                 {9, 5, 3, 2},
                 {6, 3, 1, 2}};
  sortRowWise(m);
}


Output:

1 7 8 9 
0 2 3 7 
2 3 5 9 
1 2 3 6 

Time complexity: O(N*M).
Auxiliary Space: O(1) 



Last Updated : 27 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads