之前我们所写的冒泡排序是只能对数按升序或降序排列,现在我们用模板类来对冒泡函数进行扩展,使其同时实现升序和降序排列。
具体的实现如下:
#include<iostream>
using namespace std;
template<class T>
struct Less
{
bool operator()(const T&left, const T&right)
{
return left < right;
}
};
template<class T>
struct Greater
{
bool operator()(const T&left, const T&right)
{
return left > right;
}
};
template<class T,class compare=Less<T>>
void Bubblesort(T*array, int sz)
{
bool Ischange = false;
for (int i = 0; i < sz - 1; i++)
{
bool Ischange = false;//每次都置成false
for (int j = 0; j < sz - 1 - i; j++)
{
if (compare()(array[j], array[j + 1]))
swap(array[j], array[j + 1]);
Ischange = true;
}
if (Ischange == false)
{
break;
}
}
for (int i = 0; i < sz; i++)
{
cout << array[i] << "";
}
}
void test()
{
int array[] = { 1, 5, 0, 2, 9, 4, 7, 3, 6, 8 };
int sz = sizeof(array) / sizeof(array[0]);
cout << "升序排列为:";
Bubblesort<int, Greater<int>>(array, sz);
cout << endl;
cout << "降序排列为:";
Bubblesort<int, Less<int>>(array, sz);
}
int main()
{
test();
system("pause");
return 0;
}
运行结果为: