数列有序!
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数m,请将该数插入到序列中,并使新的序列仍然有序。
Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0表示输入数据的结束,本行不做处理。
Output
对于每个测试实例,输出插入新的元素后的数列。
Example Input
3 3 1 2 4 0 0
Example Output
1 2 3 4
Hint
Author
HDOJ
参考代码
#include<stdio.h>
int main()
{
int a[100];
int n,m;
int i,j;
int temp;
while(~scanf("%d%d",&n,&m) && (n || m))
{
for(i = 0; i < n; i++)
scanf("%d",&a[i]);
a[n] = m;
for(i = 0; i < n; i++)
{
for(j = i + 1; j <= n; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for(i = 0; i <= n; i++)
{
if(i == n)
printf("%d\n",a[i]);
else
printf("%d ",a[i]);
}
}
return 0;
}
本文介绍了一个简单的算法问题:如何在一个已排序的整数数列中插入一个新的整数,使得数列保持有序状态。该算法适用于小规模数据处理,通过不断比较和交换位置来实现插入操作。
1506

被折叠的 条评论
为什么被折叠?



