C++模板实现通用冒泡排序

来源:互联网 发布:营销推广软件破解版 编辑:程序博客网 时间:2024/05/16 00:49
#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>using namespace std;#if 1#include<algorithm>#include<functional>template<class T>class Less{public:    bool operator()(const T& left, const T& right)    {        return left < right;    }};template<class T>class Greater{public:    bool operator()(const T& left, const T& right)    {        return left > right;    }};template<class Iterator,class Compare>void Bubble(Iterator first, Iterator last,Compare com){    bool IsChange = false;    while (first != last)    {        IsChange = false;        Iterator cur = first;        Iterator next = cur+1;        while (next != last)        {            if (!com(*cur,*next))            {                swap(*cur, *next);                IsChange = true;            }            cur = next;            ++next;        }        if (!IsChange)            return;        --last;    }}int main(){    int arr[] = { 4, 3, 2, 5, 9, 8, 7, 6, 1, 0 };    int i = 0;    Bubble(arr, (arr + sizeof(arr) / sizeof(arr[0])), Less<int>());    for (i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)    {        cout << arr[i] << " ";    }    cout << endl;    return 0;}#endif
原创粉丝点击