How do you sort matrices in C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do you sort matrices in C++?

How can I sort a matrix, stored as an array of integers, by row? For example, given the matrix: 3 1 2 1 6 4 2 4 7 I'd like to sort it by the correct order of the first row, keeping all the columns in their current status and turning it into: 1 2 3 6 4 1 4 7 2 I've tried several times by using the command sort, including the library algorithm, typing: sort(&A[0][0], &A[0][2]); //A is my matrix but it just order each each line, without then moving the elements underneath the first line consequently. I'm new to C++ and I don't know much about it, I've also tried by writing a different version of InsertionSort to achieve this specifical result, and it works but changes some numbers in some way that I can't understand. Is there a simple way to achieve this result with basic commands? Or, is there anything I may be doing in the wrong way?

18th Oct 2019, 8:44 PM
Alessio
Alessio - avatar
2 Answers
+ 4
Depends on what you are using as a container for your matrix. As long as you are using a container from the STL (looking at std::array or std::vector), the task is fairly simple to solve. Step 1 would be to transpose the matrix, afterwards you can just call std::sort on the entire matrix, because vectors are automatically compared first by size and, if the sizes equal (as they should in a matrix, you don't want rows with differing lengths), compared element-wise. Since you compare the vectors, they are moved as rows and the column order is preserved. Lastly, all you have to do is to transpose the matrix again, and you're done. Here is an example program, utilizing vectors as the underlying storage container: https://code.sololearn.com/cd1O82JAWB8N/?ref=app However, if you (for some reason) want to use plain arrays, well, the strategy remains the same, it's just harder to implement because you have to do everything by hand.
18th Oct 2019, 10:04 PM
Shadow
Shadow - avatar
+ 1
Thank you both, I think I'm going to try Shadow's solution since it seems pretty fast and clear, you've been very helpful!
18th Oct 2019, 10:19 PM
Alessio
Alessio - avatar