数列有序!

2018-12-14  本文已影响0人  一座城_WanG

Problem Description

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

Input

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

Output

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

Sample Input

<pre style="font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; white-space: pre-wrap; word-wrap: break-word;">

3 3
1 2 4
0 0

</pre>

Sample Output

<pre style="font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; white-space: pre-wrap; word-wrap: break-word;">

1 2 3 4

</pre>

Author

lcy

Source

C语言程序设计练习(三)

Recommend

lcy

问题简述:输入一个n(n<=100),说明有n个整数,输入n个整数时,应该让其从小到大排序好,向其中插入一个整数X,要求插入后能够实现变化后的数列仍然有序。

问题分析:我们只需要定义一个动态数组元素个数为n+1,将x赋值给第n+1个元素,将新的数列进行冒泡排序,然后输出即可。

ACC++代码如下

#include<iostream>
using namespace std;
void bubble(int *a, const int n)
{
    for (int l = 0; l < n - 1; l++)
    {
        for (int i = 0; i < n - 1; i++)
        {
            if (a[i] > a[i + 1])
            {
                int t = a[i + 1];
                a[i + 1] = a[i];
                a[i] = t;
            }
        }
    }
}
void charu(int m, int *a, const int n)
{
    a[n] = m;
    bubble(a, n + 1);
    for (int i = 0; i <= n; i++)
    {
        cout << a[i];
        if (i != n)
        {
            cout << ' ';
        }
    }
    cout << endl;
}
int main()
{
    int n, m;
    while (cin >> n >> m)
    {
        int * p = new int[n+1];
        if (n == 0 && m == 0)
        {
            break;
        }
        else
            for (int i = 0; i < n; i++)
            {
                cin >> p[i];
            }
        charu(m, p, n);
    }   
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读