Program for Row wise sorting of Matrix

In this tutorial, we will learn about the Program for Row wise sorting of Matrix in C++. Firstly we will learn about matrix and its insertion. Then sort the matrix row-wise.

Introduction

Matrix is a rectangular array of numbers that are arranged in the form of rows and columns. The total number of elements in a matrix is product between the number of rows and number of columns. To sort the matrix we have to sort every single row one row at a time.

Before sorting we have to get the data from input. To get the data we will use two loops one inner and one outer loop.

Demonstration:

#include<iostream>

using namespace std;

int main(){
  
  int matrix[10][10];
  
  cout<<"Enter the data : "<<endl;
  
  for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
      cin>>matrix[i][j];
    }
  }
  ]
  cout<<endl;
  
  for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
      cout<<matrix[i][j]<<" ";
    }
    cout<<endl;
  }
  
  return 0;
}

In the above code, we use two loops one to change the rows and one to change columns.

Program for row-wise sorting of matrix in C++

Code:

#include <bits/stdc++.h> 
using namespace std; 
  
#define SIZE 10 

void sort(int mat[SIZE][SIZE], int n) 
{ 
    int temp[n * n]; 
    int k = 0; 

    for (int i = 0; i < n; i++) 
        for (int j = 0; j < n; j++) 
            temp[k++] = mat[i][j]; 

    sort(temp, temp + k); 

    k = 0; 
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < n; j++) 
            mat[i][j] = temp[k++]; 
} 
  
void print(int mat[SIZE][SIZE], int n) 
{ 
    for (int i = 0; i < n; i++) { 
        for (int j = 0; j < n; j++) 
            cout << mat[i][j] << " "; 
        cout << endl; 
    } 
} 

int main() 
{ 
    int mat[SIZE][SIZE] ;
  int n;
    
    cout<<"Enter the dimension of matrix : ";
    cin>>n;
    
    for(int i=0;i<n;i++){
    	for(int j=0;j<n;j++){
    		cin>>mat[i][j];
    }
  }
  
    cout << "Original Matrix:\n"; 
    print(mat, n); 
  
    sort(mat, n); 
  
    cout << "\nMatrix After Sorting:\n"; 
    print(mat, n); 
  
    return 0; 
}

Input and Output:

Enter the dimension of matrix : 2
2
3
6
1
Original Matrix:
2 3
6 1

Matrix After Sorting:
1 2
3 6

Explanation:

Firstly we take input of the data.

Secondly, we call sort function. Sort function takes arguments matrix and dimension. An array is created with size of matrix then it is filled with the data of matrix. Then it is sorted like an ordinary array. After sorting it is inserted back to the matrix.

Therefore the matrix is sorted.

Conclusion

This was the program for row-wise sorting of the matrix. We can also use the same method for the sorting of one-dimensional array.

Also See:

Quick Sort in C++

Leave a Reply

Your email address will not be published. Required fields are marked *