在数组中的稳定分离为两类元素两类、组中、元素、稳定

2023-09-10 22:39:41 作者:战场英雄袍

考虑以下问题

我们给出属于一个两个类元素的数组:红色或蓝色。我们必须重新排列数组中的元素,使所有的蓝色元素是第一位的(和所有的红色元素跟随)。重排必须做的是稳定的方式,这意味着蓝色元素的相对顺序必须preserved(同样为红色的)。

We are given an array of elements belonging to one two classes: either red or blue. We have to rearrange the elements of the array so that all blue elements come first (and all red elements follow). The rearrangement must be done is stable fashion, meaning that the relative order of blue elements must be preserved (same for red ones).

有一个聪明的算法,将执行就地上述重排?

Is there a clever algorithm that would perform the above rearrangement in-place?

一个不到位的解决方案,当然,简单明了。

A non-in place solution is, of course, straightforward.

这是明显的就地解决方案将是任何稳定的排序算法应用到阵列。然而,使用一个完整的排序算法对数组的直观感觉就像矫枉过正,尤其是考虑到这一事实,我们只处理两类元素。

An obvious in-place solution would be to apply any stable sorting algorithm to the array. However, using a full-fledged sorting algorithm on an array intuitively feels like an overkill, especially taking into account the fact that we are only dealing with two classes of elements.

任何想法大大AP preciated。

Any ideas greatly appreciated.

推荐答案

这是可能做到在O(n)时间及O(1)空间明显。本文稳定的最小空间分区由Jyrki 的线性时间Katajainen和托米帕萨宁声称自己是能够做到这一点。

It is possible to do it in O(n) time and O(1) space apparently. The paper Stable minimum space partitioning in linear time by Jyrki Katajainen, and Tomi Pasanen claims to be able to do it.

谷歌稳定0-1排序。