用模板和仿函数实现一个冒泡排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZWE7616175/article/details/82316259

冒泡排序是我们初学排序时最熟悉不过的了,几乎人人都会写,建议大家写冒泡排序时,可以加上仿函数和模板进行编写,在以后的过程中使用会比较方便。而且一般的冒泡排序的时间复杂度为O(N^2),为了尽量优化我们的算法,可以定义一个bool变量,如果在一次排序后,没有进行交换,就直接跳出。

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 BubbleSort(T* arr, int size)
{
    if (arr == NULL || size<=1)
        return;

    bool IsChange = false;
    for (int i = 0; i < size - 1; ++i){
        for (int j = 0; j < size - i - 1; ++j){
            if (Compare()(arr[j], arr[j + 1])){
                IsChange = true;
                swap(arr[j], arr[j + 1]);
            }
        }
        if (IsChange == false)
            return;
    }
}

int main()
{
    int arr[] = { 3, 2, 1, 4, 8, 5 };
    BubbleSort<int, greater<int>>(arr, sizeof(arr) / sizeof(arr[0]));
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){
        cout << arr[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ZWE7616175/article/details/82316259
今日推荐