Hello. There was a problem when sorting a two-dimensional array by columns. I made the rows, the columns did not work.
You should get something like this:
Help me please.
Hello. There was a problem when sorting a two-dimensional array by columns. I made the rows, the columns did not work.
You should get something like this:
Help me please.
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
Sort all the elements of the matrix (as a one-dimensional array), and then fill out from it (a sorted one-dimensional array) the matrix by columns (in the example, three elements per column).
Example:
#include <vector> #include <algorithm> #include <iostream> int main() { const int nRow = 3; const int nCol = 4; std::vector< std::vector <int> > array = { {1, 3, 2, 4}, {5, 8, 6, 7}, {9, 12, 11, 10} }; std::vector<int> oneDimensionalArray; for (const auto& row: array){ for (const auto& element: row){ oneDimensionalArray.push_back(element); } } std::sort(oneDimensionalArray.begin(), oneDimensionalArray.end()); int i = 0; for (int c = 0; c < nCol; c++){ for (int r = 0; r < nRow; r++){ array[r][c] = oneDimensionalArray[i]; i++; } } for (int r = 0; r < nRow; r++){ for (int c = 0; c < nCol; c++){ std::cout << array[r][c] << " "; } std::cout << std::endl; } return 0; } Conclusion:
1 4 7 10 2 5 8 11 3 6 9 12 But this is based on an example. Even your wording (without looking at an example) can be understood as sorting each column separately, then it should be done differently.
easy
#include <iostream> #include <valarray> using namespace std; int main() { const int row = 3, col = 4; int m[row][col] = {{1, 3, 2, 4}, {5, 8, 6, 7}, {9, 12, 11, 10}}; std::sort(m[0], &m[row][0]); valarray<int> v(m[0], row * col), res(row * col); for (int i = 0; i < col; ++i) res[slice(i , row, col)] = v[slice(i * row, row, 1)]; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { m[i][j] = res[i * col + j]; cout << m[i][j] << ' '; } cout << endl; } return 0; } although if you don’t need an array, you can remove it and immediately initialize valarray<int> v(row * col) and sort it from &v[0] to &v[row * col] , and the result will be res (and in a loop, output res[i * col + j] ), and the code will be shorter ...
Source: https://ru.stackoverflow.com/questions/791593/
All Articles