题目传送门
1 /*
2 BubbleSort_2(),_3()为优化版
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 BubbleSort(int *a, int n)
17 {
18 for (int i=1; i<=n-1; ++i)
19 {
20 for (int j=1; j<=n-i; ++j)
21 {
22 if (a[j] > a[j+1]) swap (a[j], a[j+1]);
23 }
24 }
25 }
26
27 void BubbleSort_2(int *a, int n) //若不进行交换,已排好序,算法结束
28 {
29
30 for (int i=1; i<=n-1; ++i)
31 {
32 int pos = 0;
33 for (int j=1; j<=n-i; ++j)
34 {
35 if (a[j] > a[j+1])
36 {
37 swap (a[j], a[j+1]);
38 pos = j;
39 }
40 }
41 if (pos == 0) break;
42 }
43 }
44
45 void BubbleSort_3(int *a, int n) //一次冒泡得到最大值和最小值,排序次数几乎减少一半
46 {
47 int l = 1, r = n;
48 while (l < r)
49 {
50 for (int i=l; i<r; ++i) //正向冒泡
51 {
52 if (a[i] > a[i+1]) swap (a[i], a[i+1]);
53 }
54 --r;
55 for (int i=r; i>l; --i) //反向冒泡
56 {
57 if (a[i] < a[i-1]) swap (a[i], a[i-1]);
58 }
59 ++l;
60 }
61 }
62
63 int main(void)
64 {
65 //freopen ("rand_small.in", "r", stdin);
66 int n;
67
68 while (scanf ("%d", &n) != EOF)
69 {
70 if (n == 0)
71 continue;
72 for (int i=1; i<=n; ++i)
73 {
74 scanf ("%d", &a[i]);
75 }
76
77 BubbleSort (a, n);
78 //BubbleSort_2 (a, n);
79 //BubbleSort_3 (a, n);
80
81 bool flag = true;
82 for (int i=1; i<=n; ++i)
83 {
84 if (flag)
85 {
86 printf ("%d", a[i]);
87 flag = false;
88 }
89 else
90 printf (" %d", a[i]);
91 }
92 puts ("");
93 }
94
95 return 0;
96 }