基础算法:堆排序

上代码:

//
// 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();
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;
        while (!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

猜你喜欢

转载自www.cnblogs.com/DevilInChina/p/9375255.html