数列有序!

数列有序!

有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。

Input

输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。

Output

对于每个测试实例,输出插入新的元素后的数列。

Sample Input

3 3
1 2 4
0 0

Sample Output

1 2 3 4

C++编写:

初步代码:

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    int num[100];
    while(cin>>a>>b)
    {
        if(a == 0 && b == 0)   break;
        else
        {
            for(int i=0;i<a;i++)
            cin>>num[i];
            num[a]=b;
            for(int j=a;j>0;j--)
            {
                if(num[j-1] > num[j])
                {
                    int temp = num[j-1];
                    num[j-1] = num[j];
                    num[j] = temp;
                } 
            }
        }
        for(int k=0;k<a;k++)
        {
            cout<<num[k]<<" ";
        }
        cout<<num[a]<<endl;
    }
}

稍微优化后的代码:

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    int num[100];
    while(cin>>a>>b)
    {
        if(a == 0 && b == 0)   break;
        else
        {
            for(int i=0;i<a;i++)
            cin>>num[i];
            num[a]=b;
            int j = a;
            while(j)
            {
                if(num[j-1] > num[j])
                {
                    int temp = num[j-1];
                    num[j-1] = num[j];
                    num[j] = temp;
                    j--;
                } 
                else
                break;
            }
        }
        for(int k=0;k<a;k++)
        {
            cout<<num[k]<<" ";
        }
        cout<<num[a]<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值