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

#define _CRT_SECURE_NO_WARNINGS 1
#include
using namespace std;

#if 1
#include
#include
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

你可能感兴趣的:(编程语言)