数组按元素正负性稳定排序

问题描述:

Give you an array which has n integers,it has both positive and negative integers.Now you need sort this array in a special way.After that,the negative integers should in the front,and the positive integers should in the back.Also the relative position should not be changed.
eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.

解答一: 时空复杂度均为O(n)

算法:

    1. 扫描数组获得正数的个数countP, countN=0
    2. 申请额外的数组output[n].  从左到右,针对每个元素,若其为正数,

   if arr[i] > 0 then output[countP] = arr[i]; countP++
   if arr[i] < 0 then output[countN] = arr[i]; countN++

解答二:时间复杂度为O(n* lg n) 空间复杂度为O(1)

算法:

借鉴归并排序的思想,递归将原问题分为两个子问题,合并的时候按照下面的方法。

设需要归并的子数组为A和B,A=A1A2,A1为数组中负数部分,A2为数组中的正数部分。同理B=B1B2.我们需要得到A1B1A2B2,怎么办呢。首先,将A2, B1翻转一下,获得A2’ 和B1’,然后将A2’B1’这个整体翻转一下变获得了B1A2.于是我们目的达到了。

算法复杂度分析:

由于翻转只需使用线性时间和常数空间,故而时间复杂度参照归并排序为O(n* lg n).

原文地址:https://www.cnblogs.com/xubenben/p/3381776.html