使用模板实现冒泡法

来源:互联网 发布:淘宝买兔子红烧 编辑:程序博客网 时间:2024/06/04 17:49

                                                             使用模板实现冒泡法

之前的冒泡法可以排序一种类型,学习模板类后,我们可以使用模板实现各种类型的比较,以及需要比较sz个字符

代码如下:

#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>void Bubble_Sort(T *array, int sz){if (*array == NULL)               //空指针return;if (sz <= 1)                      //空数组或只有一个数return;int i = 0;int j = 0;bool IsChange = false;for (i = 0; i < sz - 1; i++){IsChange = false;for (j = 0; j < sz - 1 - i; j++){if (Compare()(array[j], array[j + 1])){IsChange = true;swap(array[j], array[j + 1]);}}if (IsChange == false)return;}}void test(){int array[] = { 1, 2, 4, 7, 3, 6, 5, 8, 9 };int sz = sizeof(array) / sizeof(array[0]);Bubble_Sort<int, Greater<int>>(array, sz);for (int i = 0; i < sz; i++){cout << array[i] << " ";}}int main(){test();system("pause");return 0;}

原创粉丝点击