笔试题 相对位置不变的正负数排序

  笔试题目:假设一整型数组存在若干正数和负数,现在通过某种算法使得该数组的所有负数在正数的左边,
且保证负数件和正数间元素相对位置不变。时空复杂度要求分别为:o(n),o(1)。

例如  
-3 4 2 -1 7 3 -5
排序后
-3 -1 -5 4 2 7 3

  /*1.0版本思想*/

  考虑复杂度,我的实现方法是找到第一个postive,再找到第一个negative after the postive,然后进行类似一趟冒泡的排序,重复做下去,直到cann't find negative after the first postive.

  2.0版本是对1.0版的优化

#include<stdio.h>
void swap(int *a,int *b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}
int main()
{
    int a[7]={
        -3,4,2,-1,7,3,-5
    };
    /*2.0版本*/
    int length=sizeof(a)/sizeof(int);
    int i,temp;
    for(i=0;i<length;i++){
        if(a[i]<0){
            temp=i-1;
            while(temp>=0 && a[temp]>0){
                swap(&a[temp+1],&a[temp]);
                temp--;
            }
        }
    }
    /*1.0版本 写的有点笨重*/ 
    /*
    int pos_fir=-1,p,i;
    int n=sizeof(a)/sizeof(int);
    int temp;
    
    while(a[++pos_fir]<=0);//找到第一个正数位置 
    p=pos_fir;
    
    while(p<n){
        while(a[++p]>0);//find first negative after first postive
        
        if(p<n){ //类似与一趟冒泡 
            for(i=p;i>pos_fir;i--){
                temp=a[i];
                a[i]=a[i-1];
                a[i-1]=temp;
            }
            p=pos_fir++; 
        }        
    }*/
    for(i=0;i<length;i++)
        printf("%d ",a[i]);
    
    
}

 

 

转载于:https://www.cnblogs.com/johnleo/p/neg_pos_sort.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值