zoukankan      html  css  js  c++  java
  • 基础算法:堆排序

    上代码:

    //
    // 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
  • 相关阅读:
    element input number e
    地图 scatter 自定义图片
    地图某一个区域设置高亮
    echarts 获取县级json
    echarts map 阴影(重叠)
    echarts 渐变色
    echarts tooltip 超出处理
    npm 下载 zip
    axios post 下载文件
    书签 css
  • 原文地址:https://www.cnblogs.com/DevilInChina/p/9375255.html
Copyright © 2011-2022 走看看