#include <iostream>
#include <array>
#include <iomanip>
template <typename T>
inline void swap(T * t1, T * t2) {
T tmp = *t1;
*t1 = *t2;
*t2 = tmp;
}
template <typename T, std::size_t Dim>
void bubblesort(std::array<T, Dim> & arr) {
// n -1 次
for (int i = arr.size() - 2 ; i >= 0 ; i-- ) {
// 0 -> 1 , 1-> 2, ....., i -> i+1
for (int j = 0; j <= i ; j++) {
if (arr[j] > arr[j+1]) {
swap<T>(&arr[j], &arr[j+1]);
}
}
}
}
int main() {
std::array<int, 10> arr = {{10, 8, 9, 11, 4, 2, 50, 49, 51,30}};
bubblesort<int, 10>(arr);
std::array<float, 10> arrf = {{10.2f, 8.1f, 9.f, 11.f, 2.2f, 2.1f, 2.3f, 49.f, 51.f,30.f}};
bubblesort<float, 10>(arrf);
std::cout << "int sort result" << std::endl;
for (auto & item : arr) {
std::cout << item << std::endl;
}
std::cout << "float sort result" << std::endl;
for (auto & item : arrf) {
std::cout << std::fixed << std::setprecision(2) << item << std::endl;
}
return 0;
}
编译:
g++ ./bubblesort.cpp -o test --std=c++11
运行:
int sort result
2
4
8
9
10
11
30
49
50
51
float sort result
2.10
2.20
2.30
8.10
9.00
10.20
11.00
30.00
49.00
51.00