首先,我们要知道sort()函数的使用方法:
1.需要函数头#include
2.sort(begin,end,cmp)
begin:指向待分类元素的第一个指针
end: 指向待分类元素最后一个的指针
其中end-begin是所有数的数量
cmp:表示排序的样式,没有就是默认从小到大排
要是想从大到小排,可写成greater,int也可以写成别的类型

以上是本题需要的知识。
更多的话:
可以用cmp自定义排序方式(像定义一个函数那样就行),也可以对结构体进行排序等等,自己找去吧,学无止境。

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10

分为如下几步:

首先建立一个大大的数组,并定义一个计时器

点击查看代码
int a[1000000];
int pos = 0;

然后,分别搞两个输入数的机子,目的是为了输入两个待合并排序的数组,也是为了,能够分别暂停(用-1)

点击查看代码
while(1){
   int x;
   cin>>x;
if(x=-1){
   break;
}
else{
  a[pos++]=x;
}
}

while(1){
   int y;
   cin>>y;
if(y=-1){
   break;
}
else{
  a[pos++]=y;
}
}

之后,检查一下此时计时器为多少,要是为0的话,就输出NULL,并表示不用进行排序了

点击查看代码
if(pos==0){
  cout<<"NULL";
  return 0;
}

最后,调用排序函数,进行排序

点击查看代码
sort(a,a+pos){
  for(int i=0;i<pos;i++){
    if(i==pos-1)
       cout<<a[i];
    else
       cout<<a[i];
}
  return 0;
}

完整代码:

点击查看代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int a[10000000];

int main()
{
    int pos=0;
    while(1)
    {
        int x;
        scanf("%d",&x);
        if(x==-1)
            break;
        else
            a[pos++]=x;
    }
    while(1)
    {
        int x;
        scanf("%d",&x);
        if(x==-1)
            break;
        else
            a[pos++]=x;
    }
    if(pos==0)
    {
        printf("NULL\n");
        return 0;
    }
    sort(a,a+pos);
    for(int i=0; i<pos; i++)
    {
        if(i==pos-1)
            printf("%d\n",a[i]);
        else
            printf("%d ",a[i]);
    }
    return 0;
}
posted on 2024-04-04 11:48  fafrkvit  阅读(3)  评论(0编辑  收藏  举报