基础算法:堆排序

上代码:

//
// 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

转载于:https://www.cnblogs.com/DevilInChina/p/9375255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值