通过交换对二维数组进行排序的算法

时间:2022-01-16 19:32:04

For one-dimensional arrays, sorting through swapping can be achieved easily by using Bubble sort, for example:

对于一维数组,可以使用冒泡排序轻松实现通过交换进行排序,例如:

5 4 9 8 7 1 6 3 2 10

will require 25 swaps to output

需要25次掉期才能输出

1 2 3 4 5 6 7 8 9 10

In a two-dimensional array, however, we have something like this.

然而,在二维数组中,我们有类似的东西。

4 2 3
1 8 5
7 9 6

Items can be swapped vertically and horizontally, but not diagonally:

项目可以垂直和水平交换,但不能对角交换:

  • Swap 4 and 1
  • 交换4和1
  • Swap 8 and 5
  • 交换8和5
  • Swap 8 and 6
  • 交换8和6
  • Swap 9 and 8
  • 交换9和8

This becomes the sorted array:

这成为排序数组:

1 2 3
4 5 6
7 8 9

I'm looking for an algorithm that can achieve this efficiently (minimizing the number of swaps). This problem may be similar to the 15 puzzle, though it is much simpler because every item can swap with an adjacent item and not just with the empty tile.

我正在寻找一种能够有效实现这一目标的算法(最小化交换次数)。这个问题可能类似于15拼图,虽然它更简单,因为每个项目都可以与相邻的项目交换,而不仅仅是与空的瓷砖交换。

1 个解决方案

#1


1  

In a one-dimensional array, not only does bubble-sort only ever swap adjacent elements, but it also only ever compares adjacent elements.

在一维数组中,不仅冒泡排序只交换相邻元素,而且它也只比较相邻元素。

Nothing analogous really works for a two-dimensional array, since you'd have no way to detect that

没有类似的东西真的适用于二维数组,因为你无法检测到它

1 2 4
3 5 6
7 8 9

is out of order (since you can't directly compare the non-adjacent 3 and 4).

是乱序(因为你无法直接比较不相邻的3和4)。

If we say that you can examine and compare arbitrary elements, but that the only way to update an element is to swap it with one of its neighbors, then the best approach is to start by completely figuring out where each element needs to end up (e.g., by copying the elements over to a regular array and applying a standard sorting algorithm), and only then performing the necessary swaps to move the elements to their destinations.

如果我们说您可以检查和比较任意元素,但更新元素的唯一方法是将其与其中一个邻居交换,那么最好的方法是首先完全确定每个元素需要结束的位置(例如,通过将元素复制到常规数组并应用标准排序算法),然后仅执行必要的交换以将元素移动到其目的地。

#1


1  

In a one-dimensional array, not only does bubble-sort only ever swap adjacent elements, but it also only ever compares adjacent elements.

在一维数组中,不仅冒泡排序只交换相邻元素,而且它也只比较相邻元素。

Nothing analogous really works for a two-dimensional array, since you'd have no way to detect that

没有类似的东西真的适用于二维数组,因为你无法检测到它

1 2 4
3 5 6
7 8 9

is out of order (since you can't directly compare the non-adjacent 3 and 4).

是乱序(因为你无法直接比较不相邻的3和4)。

If we say that you can examine and compare arbitrary elements, but that the only way to update an element is to swap it with one of its neighbors, then the best approach is to start by completely figuring out where each element needs to end up (e.g., by copying the elements over to a regular array and applying a standard sorting algorithm), and only then performing the necessary swaps to move the elements to their destinations.

如果我们说您可以检查和比较任意元素,但更新元素的唯一方法是将其与其中一个邻居交换,那么最好的方法是首先完全确定每个元素需要结束的位置(例如,通过将元素复制到常规数组并应用标准排序算法),然后仅执行必要的交换以将元素移动到其目的地。