C++ Online Compiler
Example: SortMatrixRowsAscColumnsDesc in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// SortMatrixRowsAscColumnsDesc #include <iostream> #include <vector> #include <algorithm> // Required for std::sort // Function to print the matrix void printMatrix(const std::vector<std::vector<int>>& matrix) { for (const auto& row : matrix) { for (int val : row) { std::cout << val << " "; } std::cout << std::endl; } } int main() { // Step 1: Define the matrix std::vector<std::vector<int>> matrix = { {3, 1, 4}, {2, 5, 0}, {7, 8, 6} }; int numRows = matrix.size(); if (numRows == 0) { std::cout << "Matrix is empty." << std::endl; return 0; } int numCols = matrix[0].size(); if (numCols == 0) { std::cout << "Matrix has empty rows." << std::endl; return 0; } std::cout << "Original Matrix:" << std::endl; printMatrix(matrix); std::cout << std::endl; // Step 2: Sort each row in ascending order for (int i = 0; i < numRows; ++i) { std::sort(matrix[i].begin(), matrix[i].end()); } std::cout << "Matrix after sorting rows (ascending):" << std::endl; printMatrix(matrix); std::cout << std::endl; // Step 3: Sort each column in descending order for (int j = 0; j < numCols; ++j) { // Extract the current column into a temporary vector std::vector<int> currentColumn; for (int i = 0; i < numRows; ++i) { currentColumn.push_back(matrix[i][j]); } // Sort the temporary column in descending order std::sort(currentColumn.begin(), currentColumn.end(), std::greater<int>()); // Place the sorted elements back into the matrix column for (int i = 0; i < numRows; ++i) { matrix[i][j] = currentColumn[i]; } } std::cout << "Matrix after sorting columns (descending):" << std::endl; printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS