zoukankan      html  css  js  c++  java
  • 堆排序模板实现

    #pragma once 
    #include<iostream>
    #include<vector>
    
    using namespace std;
    
    //仿函数定义。
    template<class T>
    struct Big
    {
        bool operator()(T x, T y)
            return x > y;
    };
    template<class T>
    struct Sma
    {
        bool operator()(T x, T y)
            return x < y;
    };
    
    //建堆的向下调整过程
    template<class T, template<class> class Cmp>
    void AdjustDown(T* arr, size_t end, int root)
    {
        if (end <= 1)
            return;
        while (root <= (end - 2) / 2)
        {
            int child = root * 2 + 1;
            //找到
            if (child + 1 < end && Cmp<T>()(arr[child] ,arr[child+1]))
            {
                child++;
            }
    
            Cmp<T>()(arr[root] ,arr[child]) ? swap(arr[root], arr[child]):(1);
            root = child;
        }
    }
    
    //堆排定义,template<class> class  typeName 定义类模板依赖。调用处就不用传入类型
    template<class T,template<class> class Cmp = Big>
    void HeapSort(T *arr,size_t size)
    {
        //建堆
        int root = (size - 2) / 2;
        while (root >= 0)
        {
            AdjustDown<T,Cmp>(arr, size, root);
            root--;
        }
        //排序
        int end = size - 1;
        while (end > 0)
        {
            swap(arr[0], arr[end]);
            AdjustDown<T,Cmp>(arr, end, 0);
            end--;
        }
    }
    
    void TestHeapSort()
    {
        int arr[] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
        int arr1[] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
        HeapSort<int, Sma>(arr, 10);
        HeapSort<int, Big>(arr1, 10);
    }
  • 相关阅读:
    2017加油
    配置SSH框架的心得
    .net 中select和where的区别
    oracle查询中文数据出现乱码
    three.js 加载 obj模型
    下载别人的3D模型文件
    关闭按钮
    桌面截屏保存成gif形式(软件)
    vue 中引入 three.js
    three.js-地球贴图-TextureLoader
  • 原文地址:https://www.cnblogs.com/lang5230/p/5318946.html
Copyright © 2011-2022 走看看