数组习题(6):有序数组中插入若干数,仍保持有序

Description

在有序的数列中插入若干个数,每插入一个数都要保持有序。

Input

输入两行,第一行输入5个有序数,第二行输入若干个插入的数,以-1结束。

Output

输出仅一行,输出所有数,用空格隔开。

Sample Input

3 5 7 9 11

15 0 8 -1

Sample Output

0 3 5 7 8 9 11 15

Source

SUBMIT

方法一

#include  <stdio.h>

int  main()

{

    int  n=5,x,i;

    int  a[20];

    for ( i = 0; i <n; i++)

    {

        scanf("%d",&a[i]);

    }

    

scanf("%d",&x);

    while (x!=-1)

    {

        

        for ( i = n-1; i>=0&&x<a[i]; i--)

        {

             a[i+1]=a[i];

        }

        a[i+1]=x;//本来是赋给a[i],但出循环时执行i--,所以这里x赋给了i+1

        n++;

        scanf("%d",&x);

    }

    for ( i = 0; i <n; i++)

    {

        printf("%d ",a[i]);

    }

    

    system("pause");

    return  0;

}

方法二

#include  <stdio.h>

#define  N   100

int  main()

{

    int  a[N],n,i,c=0,j,t;

    for ( i = 0; i <5; i++)

    {

        scanf("%d",&a[i]);

        c++;

    }

    scanf("%d",&n);

    a[c]=n;

    c++;

    while (1)

    {

        scanf("%d",&n);

         if (n==-1)

        {

            break;

        }

        else

        {a[c]=n;

        c++;}

       

       

    }

    for ( i = 0; i <c-1; i++)

    {

        for ( j = c-1; j>0; j--)

        {

            if (a[j]<a[j-1])

            {

                t=a[j];

                a[j]=a[j-1];

                a[j-1]=t;

            }

           

        }

       

    }

    for ( i = 0; i <c; i++)

    {

        printf("%d ",a[i]);

    }

       

    system("pause");

    return  0 ;

}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值