Sorting 2D arrays

So I'm in the middle of a program... part of it requires me to write a funtion to take a 2D array (maximum 20x20) from a file and sort each row. For example:
9 4 2 1 would become 1 2 4 9
3 5 6 2 -------------------2 3 5 6

Also, I need to write another function to sort the columns of a 2D array in descending order.
1 2 3 would become 7 8 9
4 5 6 -------------------4 5 6
7 8 9 -------------------1 2 3

I am having trouble forming the logic to complete these functions. Any help would be much appreciated.
Last edited on
2D Arrays to Array -> stort Array -> build 2D Arrays

[1,2,3]
[4,5,6]
[7,8,9]
->
[1,2,3,4,5,6,7,8,9]
->
[9,8,7,6,5,4,3,2,1]
->
[7,8,9]
[4,5,6]
[1,2,3]
@monkey11: that's no help at all

@topic: for the first sort you need 1 for loop, 1variable to save the maximum of each run, 1variable to swap elements of that array.
try to find the maximum of all elements in the first run and swap it to the highest index. in the next run of your for loop your aim is to find the 2nd highest number and swap it to the 2nd highest index. so basically try to find the maximal, save it at the highest index and dont change it again.

for the 2nd sort the idea stays the same, but you need 2 for loops now. 1 to run through the rows and 1 for the colums.

if you can't figure out how to solve it, ask again.
closed account (D80DSL3A)
If you can sort a 1D array then you've got this.

Given int mat[rows][cols];

First, sort this 1D array (you are varying only the 2nd index)
mat[0][i]// row 0

then this one:
mat[1][i]

and so on through:
mat[rows-1][i]

Now the rows are sorted.

Repeat above with:
mat[i][0];// sort column 0
then
mat[i][1]
through
mat[i][cols-1]

And you are done!


The first is trivial: just call sort() on every row.

1
2
3
4
5
6
template<size_t R, size_t C>
void sort_every_row(int (&a)[R][C])
{
    for(size_t r = 0; r < R; ++r)   // or,  classier, for(auto& row : a) 
        std::sort(a[r], a[r] + C);  //                    boost::sort(row);
}


online demo: http://ideone.com/cW3nHy

For the second one, sort works if you can provide a view that represents each column as its own sequence. For example :

1
2
3
4
5
6
7
8
template<size_t R, size_t C>
void sort_every_col(int (&a)[R][C])
{
    using namespace boost::adaptors;
    for(size_t c = 0; c < C; ++c)
        sort(boost::make_iterator_range(&a[0][0]+c, &a[0][0]+R*C) | strided(C),
             std::greater<int>());
}

no boost range on ideone, so here's a demo that uses an array of pointers : http://ideone.com/1Wpjh9
Last edited on
Topic archived. No new replies allowed.