问题 B: 调整表中元素顺序(线性表)

来源:互联网 发布:python 求指数 编辑:程序博客网 时间:2024/05/18 04:56

问题 B: 调整表中元素顺序(线性表)

时间限制: 1 Sec  内存限制: 2 MB
提交: 28  解决: 11
[提交][状态][讨论版]

题目描述

若一个线性表L采用顺序存储结构存储,其中所有元素都为整数。设计一个算法,将所有小于0的元素移到所有大于0的元素前面,要求算法的时间复杂度不超过O(nlog(n)),空间复杂度为O(1)。

  

顺序表的定义为:

typedef struct
{
    ElemType data[SizeMax];
    int length;
} SqList;
  
需编写的算法为:
void move(SqList *&L);
  

注意:只需提交你所编写的算法即可

输入

输入的数据有两行,第一行输入线性表的长度n,第二行依次输入n个元素。

输出

输出的数据占一行,为调整之后的线性表,每个元素中间用空格分隔。

样例输入

10-12 25 -19 21 -18 -11 5 -18 9 -22

样例输出

-12 -19 -18 -11 -18 -22 25 21 5 9

提示

1、请选择C++提交


2、注意调整后元素的顺序


3、只需提交调整顺序表元素的算法(move函数)

#include <stdio.h>#include <stdlib.h>#include <algorithm>#define SizeMax 100000using namespace std;typedef int ElemType;typedef struct{    ElemType data[SizeMax];    int length;} SqList;void CreateList(SqList *&L,ElemType n){    if(n>SizeMax)return;    L=(SqList*)malloc(sizeof(SqList));    for(int i=0; i<n; i++)        scanf("%d",&L->data[i]);    L->length=n;}void move(SqList *&L){    int n=L->length,a[10000],m;    for(int i=0,j=0,r=0;i<n;i++)    {        if(L->data[i]<0)            {                L->data[j]=L->data[i];                j++;            }        else        {            a[r]=L->data[i];            r++;        }         m=j;    }    for(int i=m,r=0;i<n;i++)    {        L->data[i]=a[r];        r++;    }}void Print(SqList *L){    for(int i=0; i<L->length; i++)        printf(i!=L->length-1?"%d ":"%d\n",L->data[i]);}int main(){    SqList *L;    ElemType n;    scanf("%d",&n);    CreateList(L,n);    move(L);    Print(L);    free(L);    return 0;}


0 0