# Thread: Pseudocode for sorting a 2d array?

1. ## Pseudocode for sorting a 2d array?

A B C D
192 48 206 37
147 90 312 21
186 12 121 38
114 21 408 39
267 13 382 29
906 184 1429 164

As i'm swapping the columns. (char A,B,C,D) are not part of the numbers array.
How can i ensure that the letters are swapped accordingly?

2. Originally Posted by tmac619619
I understand how to sort the last row.
So, use your understanding and, in the same way, sort the first row, the 2nd row, ...

3. Correct me if my psuedocode s wrong:

1. compare the last row values.

2. And based off of that 1 value alone. Swap an entire column?

4. Ah! Sorry, I misunderstood the requirements: I thought you wanted to sort all rows in the same manner.

If I understand you correctly, you want to sort the totals only; but want to move each column to its proper place to get the same total.
To do that, rather than sorting the values themselves, get another array with indices and sort the indices according to the totals. Then print each row with the indices ...

row1: 192 48 206 37
row2: 147 90 312 21
row3: 186 12 121 38
row4: 114 21 408 39
row5: 267 13 382 29
totals: 906 184 1429 164
indices: 1 2 3 4
sorted indices according to totals: 4 2 1 3 (corresponding to 164 184 906 1429)
row1 (by 'sorted' indices): 37 48 192 206
row2 (by 'sorted' indices): 21 90 147 312
row3 (by 'sorted' indices): 38 12 186 121
row4 (by 'sorted' indices): 39 21 114 408
row5 (by 'sorted' indices): 29 13 267 382

5. Originally Posted by qny
Ah! Sorry, I misunderstood the requirements: I thought you wanted to sort all rows in the same manner.

If I understand you correctly, you want to sort the totals only; but want to move each column to its proper place to get the same total.
To do that, rather than sorting the values themselves, get another array with indices and sort the indices according to the totals. Then print each row with the indices ...

row1: 192 48 206 37
row2: 147 90 312 21
row3: 186 12 121 38
row4: 114 21 408 39
row5: 267 13 382 29
totals: 906 184 1429 164
indices: 1 2 3 4
sorted indices according to totals: 4 2 1 3 (corresponding to 164 184 906 1429)
row1 (by 'sorted' indices): 37 48 192 206
row2 (by 'sorted' indices): 21 90 147 312
row3 (by 'sorted' indices): 38 12 186 121
row4 (by 'sorted' indices): 39 21 114 408
row5 (by 'sorted' indices): 29 13 267 382
Ok that's great. But how would i account for the letters A,B,C,D?

6. You could think of it as a sort of 4 structs, only. Each struct has a column's worth of an 1D array, and a char. Your array would be an array of 4 structs, or you could just handle the structs individually by their totals, and forget the array for them.

Or use a parallel char array. Whenever you swap column A, you swap the matching char A, in the parallel array, in the same way.