Answer the question
In order to leave comments, you need to log in
How to sort a 2D array by columns?
Good day, the question arose of how to sort a two-dimensional array by columns (example below). Mandatory condition: do not use additional arrays and .
Thank you in advance!
Answer the question
In order to leave comments, you need to log in
Treat an array as if it were one-dimensional. Number it like this: the first indexes are the first column from top to bottom. Then there are indexes with cells in the second column, and so on.
You are left with one number - the index in this virtual one-dimensional array to receive the indices of the original two-dimensional array.
The column number will be i / M
, where M is the number of rows. The line number will be i % M
.
You only need to write an algorithm for sorting a one-dimensional array, and wherever there is a reference to [i], you need to do [i % M][i / M].
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question