In this program, we are going to share a C++ implementation to sort the given matrix. If you are a beginner and want to start learning the C++ programming, then keep your close attention in this tutorial as I am going to share a program for C++ implementation to sort the given matrix.
Copy the below C++ program and execute it with the help of GCC compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <bits/stdc++.h> using namespace std; #define SIZE 10 // function to sort the given matrix void sortMat(int mat[SIZE][SIZE], int n) { // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix void printMat(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; } } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMat(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0; } |
Original Matrix:
5 4 7
1 3 8
2 9 6
Matrix After Sorting:
1 2 3
4 5 6
7 8 9
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.