How to sort an integer array into negative, zero, positive part without changing relative position?

前端 未结 5 1401
梦毁少年i
梦毁少年i 2021-02-04 08:31

Give an O(n) algorithm which takes as input an array S, then divides S into three sets: negatives, zeros, and positives. Show how to implement this in place, that is, without a

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 09:11

    Can't this be done simply using any "stable sort" performed with a custom comparitor which only checks the sign?

    Edit:
    No, that's O(n log n).

    One thing you can do in linear time is reduce the problem. Since the zeros can't be ordered (how do you tell one from the other?), you can make a pass where you walk through the array, skipping the zeroes and filling in with the non-zero values. Then add the correct number of zeros at the end.

    j=0;
    for (i=0;i

    Now you can ignore the last section and the problem becomes finding an O(n) algorithm for a stable partition around 0. Unfortunately, the stable_partition function from the c++ stl has only O(n) comparisons, but O(n log n) swaps if no additional space is available.

    However, this article: "Stable minimum space partitioning in linear time" seems to indicate that it is possible in O(n). I don't think I understand it well enough to summarize it clearly here.

    If that works, The final step is to insert the zeros back inbetween the partitions, which is also O(n), since the zeros have no order to maintain.

提交回复
热议问题