【排序算法】冒泡排序

无意翻出了以前写的排序
开个坑,用C++造轮子系列。。
为了凸显自己造轮子,不使用algorithm标准库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 133.冒泡排序.cpp
// http://nanti.jisuanke.com/t/133

#include <iostream>
#include <vector>
using namespace std;

template <typename T>
void mySwap(T &a, T &b)
{
T t(a);
a = b;
b = t;
}

template <typename T>
void myDisplay(typename T::const_iterator begin, typename T::const_iterator end, ostream &os = std::cout)
{
while (begin != end - 1)
{
os << *begin << " ";
begin++;
}
os << *begin;
}

template <typename t>
int bubbleSort(vector<t> &data)
{
int total = 0;
int cnt = 0;
do
{
typename vector<t>::size_type j = 0;
cnt = 0;
for (typename vector<t>::size_type i = 0; i < data.size() - 1 - j; i++)
{
if (data[i] > data[i + 1])
{
mySwap(data[i], data[i + 1]);
cnt++;
}
}
j++;
total += cnt;
} while (cnt > 0);
return total;
}

int main()
{
vector<int> data;
int t;
while (cin >> t)
{
data.push_back(t);
}
bubbleSort(data);
myDisplay< vector<int> > (data.begin(), data.end());
return 0;
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信