Algorithm for sorting a two-dimensional array by replacing

For one-dimensional arrays, swap sorting can be easily achieved using Bubble sorting, for example:

5 4 9 8 7 1 6 3 2 10

25 swaps required for withdrawal

1 2 3 4 5 6 7 8 9 10

However, in a two-dimensional array, we have something like this.

4 2 3
1 8 5
7 9 6

Elements can be changed vertically and horizontally, but not diagonally:

  • Exchange 4 and 1
  • Exchange 8 and 5
  • Exchange 8 and 6
  • Exchange 9 and 8

This becomes a sorted array:

1 2 3
4 5 6
7 8 9

I am looking for an algorithm that can do this effectively (minimizing the number of swaps). This problem may be similar to puzzle 15, although it is much simpler because each element can be changed using an adjacent element, and not just with empty tiles.

+4
1

, .

, ,

1 2 4
3 5 6
7 8 9

( 3 4).

, , - , - , (, ) .

+1

Source: https://habr.com/ru/post/1624683/


All Articles