排序算法之插入排序

 

题目传送门

 1 /*
 2     插入排序——扑克牌排序
 3     用zstu3539题目来验证算法的正确性
 4 */
 5 #include <cstdio>
 6 #include <iostream>
 7 #include <algorithm>
 8 #include <ctime>
 9 #include <cstdlib>
10 using namespace std;
11 
12 const int maxn = 1000000 + 10;
13 const int INF = 0x3f3f3f3f;
14 int a[maxn];
15 
16 void InsertSort(int *a, int n)
17 {
18     for (int i=2; i<=n; ++i)
19     {
20         if (a[i-1] > a[i])
21         {
22             int x = a[i];
23             int j = i - 1;
24             while (j > 0 && a[j] > x)
25             {
26                 a[j+1] = a[j];
27                 --j;
28             }
29             a[j+1] = x;
30         }
31     }
32 }
33 
34 
35 int main(void)
36 {
37     //freopen ("rand_small.in", "r", stdin);
38     int n;
39 
40     while (scanf ("%d", &n) != EOF)
41     {
42         if (n == 0)
43             continue;
44         for (int i=1; i<=n; ++i)
45         {
46             scanf ("%d", &a[i]);
47         }
48     
49         InsertSort (a, n);
50 
51         bool flag = true;
52         for (int i=1; i<=n; ++i)
53         {
54             if (flag)
55             {
56                 printf ("%d", a[i]);
57                 flag = false;
58             }
59             else
60                 printf (" %d", a[i]);
61         }
62         puts ("");
63     }
64 
65     return 0;
66 }

 

转载于:https://www.cnblogs.com/Running-Time/p/4392134.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值