第二十七章:不改变正负数之间相对顺序重新排列数组

一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的正负数之间相对顺序。
比如: input: 1,7,-5,9,-12,15 ,ans: -5,-12,1,7,9,15 。且要求时间复杂度O(N),空间O(1) 。

没有什么很好的方法

#include <iostream>     
#include <algorithm>
#include <functional>
using namespace std;    

void sort(int* arr, int length)  
{  
    if(length < 1 || NULL == arr)  
    {  
        return;  
    }  
    int* p = arr;  
    int* q = arr;  
    int* pos = q;  

    while(p <= arr + length - 1)  
    {  
        if(*p < 0)  
        {  
            swap(*p,*q); 
            pos = q;  
            while(pos < p)  
            {  
                ++pos;  
				swap(*p,*pos);  
            }  
            ++q;  
        }  
        ++p;  
    }  
}  
int main()    
{    
	int arr[]={1,-1,3,4,-3,2,-5,9,-1,8}; 
	sort(arr,10);
	for_each(arr,arr+10,[](int i){cout<<i<<endl;});
}    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值