用模板编写冒泡排序

之前我们所写的冒泡排序是只能对数按升序或降序排列,现在我们用模板类来对冒泡函数进行扩展,使其同时实现升序和降序排列。
具体的实现如下:

#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;
}

运行结果为:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值