Given a 2D array of integers, let's sort its rows and columns in blocks. This means that you only have to sort a given row or column, but applying the transformations needed for sorting it to every other row or column in the 2D array.
Rules
- Input will be a 2D array of integers and a 1-indexed integer. This integer will represent the row to be sorted if the number is positive, or the column to be sorted if the number is negative (or the other way round you want). Example: Given a
4x3
(rows x columns) array you can sort the second column with a-2
argument or the third row with a3
argument. This second argument will never be zero and its absolute value will never be greater than the corresponding dimension of the array. - Output will be also a 2D array of integers with the needed transformations applied to sort the given row or column. Alternatively you can just write the array to STDOUT.
- The output array will have the specified row or column sorted in ascending order. Just note that when you need to swap two numbers in a row, the whole columns where the numbers lay will be swapped. And when you need to swap two numbers in a column, the whole rows where the numbers lay will be swapped.
- In the case in which the same number appears several times in the row/column to be sorted, there will be several solutions possible according to the way you swap the values, just do accordingly with the rest of rows/columns to be swapped.
Examples
Positive indices for rows and negative indices for columns
[5 8 7 6 [1 3 2 4
1 3 2 4 order by -3 (3rd column) --> 9 6 3 0
9 6 3 0] 5 8 7 6]
[5 8 7 6 [9 6 3 0
1 3 2 4 order by -4 (4th column) --> 1 3 2 4
9 6 3 0] 5 8 7 6]
[5 8 7 6 [5 7 8 6
1 3 2 4 order by 2 (2nd row) --> 1 2 3 4
9 6 3 0] 9 3 6 0]
[5 8 7 6 [6 7 8 5
1 3 2 4 order by 3 (3rd row) --> 4 2 3 1
9 6 3 0] 0 3 6 9]
[1 2 [1 2 [3 2
3 2] order by -2 (2nd column) --> 3 2] or 1 2] (both are valid)
[7 5 9 7 [5 7 7 9 [5 7 7 9
1 3 2 4 order by 1 (1st row) --> 3 1 4 2 or 3 4 1 2
9 6 3 0] 6 9 0 3] 6 0 9 3]
This is code-golf, so may the shortest code for each language win!