107 lines
1.8 KiB
C++
107 lines
1.8 KiB
C++
|
|
#include <vector>
|
|
#include <exception>
|
|
using namespace std;
|
|
|
|
|
|
|
|
template <class T>
|
|
class Heap
|
|
{
|
|
public:
|
|
typedef int (*Compare)(T , T);
|
|
|
|
private:
|
|
std::vector<T> data;
|
|
Compare compare;
|
|
|
|
public:
|
|
Heap()
|
|
{
|
|
}
|
|
|
|
Heap(Compare _compare)
|
|
{
|
|
this->compare = _compare;
|
|
}
|
|
|
|
~Heap()
|
|
{
|
|
}
|
|
|
|
|
|
|
|
void push(T value)
|
|
{
|
|
unsigned long cur_idx = this->data.size();
|
|
this->data.push_back(value);
|
|
|
|
for (;cur_idx != 0;)
|
|
{
|
|
unsigned long push_idx = (cur_idx - 1) >> 1;
|
|
T &push_value = this->data[push_idx];
|
|
if (this->compare(value, push_value) > 0)
|
|
{
|
|
this->data[cur_idx] = push_value;
|
|
cur_idx = push_idx;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
this->data[cur_idx] = value;
|
|
}
|
|
|
|
|
|
T pop() {
|
|
if(this->data.size() == 0) {
|
|
throw "size 错误";
|
|
}
|
|
T result = this->data[0];
|
|
T pvalue = this->data.pop_back();
|
|
unsigned long cur_idx = 0;
|
|
unsigned long size = this->data.size();
|
|
|
|
unsigned long c1, c2, cidx;
|
|
|
|
for(;cur_idx < size;) {
|
|
cidx = cur_idx << 1;
|
|
|
|
c2 = cidx + 2;
|
|
if(c2 < size) {
|
|
T cvalue2 = this->data[c2];
|
|
|
|
c1 = cidx + 1;
|
|
T cvalue1 = this->data[c1];
|
|
|
|
if (this->compare(cvalue1, cvalue2) >= 0 ){
|
|
cidx = c1;
|
|
cvalue = cvalue1;
|
|
} else {
|
|
cidx = c2;
|
|
cvalue = cvalue2;
|
|
}
|
|
} else {
|
|
|
|
c1 = cidx + 1
|
|
if c1 < h.size {
|
|
cvalue1 = h.elements[c1]
|
|
cidx = c1
|
|
cvalue = cvalue1
|
|
} else {
|
|
break
|
|
}
|
|
|
|
}
|
|
|
|
if h.Compare(cvalue, downvalue) > 0 {
|
|
h.elements[curidx] = cvalue
|
|
curidx = cidx
|
|
} else {
|
|
break
|
|
}
|
|
}
|
|
this->data[cur_idx] = pvalue;
|
|
return result;
|
|
}
|
|
}; |