数列有序!
Time Limit: 1000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 60632
Accepted Submission(s): 16075
Problem Description
有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
问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2019
问题简述:将一个整数按大小顺序插入到已排序好的序列当中,再将插入后的序列输出
程序说明:数组后移一位,直到找到合适的位置进新的数字插入
AC通过的c++语言程序如下:
#include"pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, m;
while (cin >> n >> m)
{
if (n == 0 && m == 0)
break;
int a[100];
for (int i = 0; i < n; i++)
cin >> a[i];
if (m > a[n - 1])
{
a[n] = m;
int t;
}
else
for(int i=n-1;i>-1;i--)
{
a[i + 1] = a[i];
if (m > a[i])
{
a[i + 1] = m;
break;
}
}
if (a[0] > m)
a[0] = m;
int t;
for (t = 0; t < n; t++)
cout << a[t] << " ";
cout << a[n] << endl;
}
}