Stable separation for two classes of elements in an array

岁酱吖の 提交于 2019-12-17 13:03:40

问题


Consider the following problem.

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.

Any ideas greatly appreciated.


回答1:


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.

Google for stable 0-1 sort.




回答2:


I don't know O(n) algorithm but here's a simple algorithm with O(n*log(n)) complexity in the worst case. Maybe it will be useful.

Cut off the zeroes from beginning and ones from the end, they are already on their places. Now the array looks like a sequence of ones followed by sequence of zeroes followed by sequence of ones and so on, like this: 1010101010

Exchange the first sequence of ones with the first sequence of zeroes, the third sequence of ones with the third sequence of zeroes and so on. It will become: 0110011001

The amount of sequences became about twice less. Repeat the above procedure until the array is sorted.

To exchange two neighbour sequences reverse the first one, then the second one, and then reverse them both.




回答3:


This is called Stable Partitioning in C++ and there is a standard algorithm for this: std::stable_partition.

The SGI implementation has an adaptive behavior depending on the amount of memory available:

  • it runs in O(N) if it's possible to allocate O(N) space
  • it runs in O(N log N) swaps in place

I do wonder if the latter in place solution uses a stable sorting algorithm behind the scenes.



来源:https://stackoverflow.com/questions/2906789/stable-separation-for-two-classes-of-elements-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!