【2013】将x插入有序数列

Time Limit: 3 second
Memory Limit: 2 MB

将一个数x插入到有序数列a中,插入后a仍然有序。

Input

第一行输入有序数列a的元素个数
第二行依次输入a的元素,以回车结束
第三行输入x的值

Output

输出插入x后的数列,每个元素用空格隔开,最后用回车结束

Sample Input

10
1 2 11 13 15 20 25 30 35 40
21

Sample Output

1 2 11 13 15 20 21 25 30 35 40

【题解】

这个插入要特别注意 小于最小值和大于最大值的情况。特判是比较明智的选择。。其他的只要for一遍

找到一个I 使得a[i] <= temp temp <= a[i+1]就好。然后从n+1开始for 到 i+2,a[j]=a[j-1];这样就能全部往后移一位。

【代码】

#include <cstdio>
#include <stdlib.h>

const int MAXN = 30000;

int n,temp,a[MAXN];

void output_ans() //把输出答案的步骤做成一个过程,方便特判。
{
    for (int i = 1;i <= n;i++)
        printf("%d ",a[i]);
    printf("%d
",a[n+1]);
}

void input_data()
{
    scanf("%d",&n);
    for (int i = 1;i <=n ;i++)
        scanf("%d",&a[i]);
    scanf("%d",&temp);
    if (temp > a[n]) //特判两种情况,即小于最小值和大于最大值的情况
        {
            a[n+1] = temp;
            output_ans();
            exit(0);
        }
    if (temp < a[1])
        {
            for (int j = n+1;j >= 2;j--)
                a[j] = a[j-1];
            a[1] = temp;
            output_ans();
            exit(0);
        }
}

void get_ans()
{
    int j;
    for (int i = 1;i <= n-1;i++) //这是判断插入的位置。寻找到题解所需要的i
        if (a[i] <= temp && temp <= a[i+1])
            {
                j = i;
                break;
            }
    for (int k = n+1;k >= j + 2;k--) //这是将所有的数字往后移动一位的方法。
        a[k] = a[k-1];
    a[j+1] = temp;
}

int main()
{
    //freopen("F:\rush.txt","r",stdin);
    input_data();
    get_ans();
    output_ans();
    return 0;
}


 

原文地址:https://www.cnblogs.com/AWCXV/p/7632481.html