代码如下
//bubble sort
template<int i,int j>
void sub_bubblesort(int *data) { //swap the biggist of i ints to the last slot
/*for (int m = 0; m < i - 1; ++m) {
if (data[m] > data[m + 1])
std::swap(data[m], data[m + 1]);
}*/
if (data[j] > data[j + 1])
std::swap(data[j], data[j + 1]);
sub_bubblesort < j < i - 1 ? i : 0, j<i - 1 ? j + 1 : 0>(data);
}
template<>
void sub_bubblesort<0, 0>(int *) {};
template<int n>
void bubblesort(int *data) {
sub_bubblesort<n-1,0>(data);
bubblesort<n - 1>(data);
}
template<>
void bubblesort<1>(int *data) {}
模板函数template<int i,int j> void sub_bubblesort(int *data)里注释掉的for循环是我第一遍根据题意自己写的,后来看代码,用模板元主要目的在于编译器代码展开,这样可以大大提高效率。然后就成了下面那个样子。根据文章里给的测试结果,用模板元代码展开比直接for循环快一倍。我没测。