Sorting makes no sense for a 2-dimensional array... or does it?
Your task is to take an input grid and apply a bubble-sort-like algorithm to it until all values in the grid are non-decreasing from left to right and top to bottom along every row and column.
The algorithm works as follows:
- Each pass goes row by row, top to bottom, comparing/swapping each cell with its right and below neighbors.
- if the cell is greater than only one of its right and below neighbors, swap with the one that it is greater than
- if the cell is greater than both its right and below neighbors, swap with the smaller neighbor
- if the cell is greater than both its right and below neighbors, which are the same value, then swap with the below neighbor.
- if the cell is not greater than either of its right and below neighbors, do nothing
- Continue this until no swaps are made throughout the entire pass. This will be when every row and column are in order, left to right and top to bottom.
Example
4 2 1 3 3 5 7 2 1 The first row of the pass will swap the 4 and the 2, then the 4 with the 1.
2 1 4 3 3 5 7 2 1 When we get the the middle 3, it will be swapped with the 2 below
2 1 4 3 2 5 7 3 1 Then the 5 gets swapped with the 1 below
2 1 4 3 2 1 7 3 5 The last row of the first pass moves the 7 all the way to the right
2 1 4 3 2 1 3 5 7 Then we go back to the top row again
1 2 1 3 2 4 3 5 7 And continue row by row...
1 2 1 2 3 4 3 5 7 ... until the grid is "sorted"
1 1 2 2 3 4 3 5 7 Another Example
3 1 1 1 1 1 1 8 9 becomes
1 1 1 1 1 1 3 8 9 rather than
1 1 1 1 1 3 1 8 9 because the downward swap takes priority when both the right and below neighbors of a cell are equal.
A step-by-step reference implementation can be found here.
Test cases
5 3 2 6 7 3 1 0 3 2 1 9 9 8 3 0 3 2 2 8 9 8 7 6 becomes
0 0 1 1 2 2 3 6 2 2 3 3 6 7 8 8 3 3 5 7 8 9 9 9 2 1 2 7 8 2 1 0 2 2 2 2 3 2 1 0 1 2 3 4 5 4 3 2 9 8 7 6 5 4 3 6 6 5 4 3 2 2 1 0 becomes
0 0 0 1 1 1 2 2 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 4 4 4 4 5 6 6 5 5 6 7 7 8 8 9 Rules
- You can take the input grid in any convenient format
- You may assume the grid values are all non-negative integers in the unsigned 16-bit range (0-65535).
- You may assume the grid is a perfect rectangle and not a jagged array. The grid will be at least 2x2.
- If you use another algorithm of sorting, you must supply a proof that it will always produce the same resulting order as this particular brand of 2D bubble sorting, no matter what the input is. I expect this to be a non-trivial proof, so you're probably better off using the described algorithm.
Happy Golfing!