数列有序!

来源:互联网 发布:手机画中画软件 编辑:程序博客网 时间:2024/06/05 04:21

数列有序!

Problem Description


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


Input

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


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


3 31 2 40 0

Example Output


1 2 3 4 5

代码:

#include <stdio.h>#include <stdlib.h>int main(){    int i, j, n, m, a[101];    while(scanf("%d%d", &n, &m) != EOF && (n || m))    {        for(i = 0; i < n; i++)            {                scanf("%d", &a[i]);            }            for(i = 0; i <= n; i++)            {                if(m < a[i])                {                    for(j = n - 1; j >= i; j--)                    {                        a[j + 1] = a[j];                    }                    a[i] = m;                    break;                }            }            for(i = 0; i <= n; i++)            {                if(i == n)                {                    printf("%d", a[i]);                }                else                {                    printf("%d ", a[i]);                }            }            printf("\n");    }    return 0;}
原创粉丝点击