Stable separation for two classes of elements in an array

删除回忆录丶 提交于 2019-11-27 15:15:46

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.

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.

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.

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