插入排序

                           **插入排序**

Problem Description

现有 n 个从小到大排列的数组成的序列。需要对这个序列进行 c 次操作。

每次操作有两种类型:

操作 1:插入一个数 v 到序列中,并保持有序。
操作 2:输出当前的序列。

bLue 并不太擅长序列操作,所以他想来请求你的帮助,你能帮助他完成这个任务吗?

Input

输入数据有多组(数据组数不超过 30),到 EOF 结束。

对于每组数据:

第 1 行输入一个整数 n (1 <= n <= 10^5),表示初始的有序序列中数字的个数。
第 2 行输入 n 个用空格隔开的整数 ai (0 <= ai <= 10^6),表示初始序列。
第 3 行输入一个整数 c (1 <= c <= 1000),表示有 c 次操作。
接下来有 c 行,每行表示一次操作:
    如果操作类型为 1,则输入格式为 "1 v",其中 v (0 <= v <= 1000) 表示要插入到序列的数。
    如果操作类型为 2,则输入格式为 "2"。

Output

对于每组数据中的每次类型为 2 的操作,输出一行,表示当前的序列,每个数之间用空格隔开。

Sample Input

5
1 2 2 3 5
5
1 0
2
1 3
1 7
2

Sample Output

0 1 2 2 3 5
0 1 2 2 3 3 5 7

参考代码

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node*next;
};
int main()
{
    int n,c,i;
    while(~scanf("%d",&n))
    {
        struct node*head,*q,*p;
        head=(struct node*)malloc(sizeof(struct node));
        head->next=NULL;
        q=head;
        for(i=0; i<n; i++)
        {
            p=(struct node*)malloc(sizeof(struct node));
            p->next=NULL;
            scanf("%d",&p->data);
            q->next=p;
            q=p;
        }
        scanf("%d",&c);
        for(i=0; i<c; i++)
        {
            int a;
            scanf("%d",&a);
            if(a==1)//1时插入
            {
                p=(struct node*)malloc(sizeof(struct node));
                p->next=NULL;
                scanf("%d",&p->data);
                q=head;
                while(q->next)
                {
                    if(q->next->data>p->data)//从头开始前一个与后一个比较,如果插入的数据小于后一个跳出循环
                    {
                        break;
                    }
                    q=q->next;
                }
                p->next=q->next;//链表插入
                q->next=p;
            }
            else{//2时输出
            p=head->next;
            printf("%d",p->data);
            p=p->next;
            while(p){
            printf(" %d",p->data);
            p=p->next;
            }
            printf("\n");
            }
        }
        p=head;//释放空间
        while(p){
        q=p->next;
        free(p);
        p=q;
        }
    }
    return 0;
}

插入排序详解

参考博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值