• 基础算法:堆排序


    上代码:

    //
    // Created by DevilInChina on 2018/6/21.
    //

    #ifndef HEAP_HEAP_CPP
    #define HEAP_HEAP_CPP
    #include <vector>
    #include <cstring>
    #include <functional>
    #include <algorithm>
    #define MAX_LEN 100000
    template <typename T>
    class Heap {
    public:
    Heap();
    Heap(std::function<bool(const T&,const T&)>);
    void push(const T &a);
    void push(T &&);
    T top(){ return *store[0]; }
    bool empty(){ return !len;}
    void pop();
    ~Heap(){
    for(int i = 0 ; i < len ; ++i){
    delete store[i];
    }
    }
    private:
    T*store[MAX_LEN];
    int len;
    std::function<bool(const T&,const T&)>grad;///比较规则,默认用 < 进行比较
    };

    template <typename T>
    Heap<T>::Heap(){
    for(int i = 0 ; i < MAX_LEN ; ++i){
    store[i] = nullptr;
    }
    len = 0;
    grad = [&](const T&a,const T&b)->bool{ return a<b;};
    }

    template <typename T>
    Heap<T>::Heap(std::function<bool(const T&,const T&)> temp) {
    for(int i = 0 ; i < MAX_LEN ; ++i){
    store[i] = nullptr;
    }
    len = 0;
    grad = temp;
    }

    template <typename T>
    void Heap<T>::push(const T &a){
    T *tmp = new T(a);
    len++;
    int i = len-1,j;
    while(i){
    j = (i-1)>>1;
    if(!grad(*store[j],a))break;
    store[i] = store[j];
    i = j;
    }
    store[i] = tmp;
    }
    template <typename T>
    void Heap<T>::push(T &&a) {/// c++11 特性,转移语意(具体特有待商榷)
    int i = len,j;
    T *tmp = new T(std::move(a));
    while (i){
    j = (i-1)>>1;
    if (!grad(*store[j],*tmp))break;
    store[i] = store[j];
    i = j;
    }
    ++len;
    store[i] = tmp;
    }

    template <typename T>
    void Heap<T>::pop() {
    int i = 0,j=1;
    T *del = store[0];
    --len;
    T *mark = store[len];
    while (j<=len){
    if(j<len&&grad(*store[j],*store[j+1]))++j;
    if(!grad(*mark,*store[j]))break;
    store[i] = store[j];
    i = j,j=i<<1|1;
    }
    store[i] = mark;
    store[len] = nullptr;
    delete del;
    }

    #endif //HEAP_HEAP_CPP
  • 相关阅读:
    当import的模块内容发生变化时,对此模块进行重新加载(刷新)
    使用python的ctypes库实现内存的动态申请和释放
    【转载】实现博客园图片的可放大功能
    使用tqdm实现下载文件进度条
    pytest参数化的两种方式
    Jmeter之Bean shell使用-常用内置变量
    JMeter之Ramp-up Period(in seconds)说明
    Jmeter性能测试基础
    接口测试基础
    JMeter做http接口功能测试
  • 原文地址:https://www.cnblogs.com/DevilInChina/p/9375255.html
Copyright © 2020-2023  润新知