Ukážme si celú implementáciu haldy v jazyku C++. Ak vám nejaké detaily neboli jasné, skúste si prejsť program a pozrieť sa, ako funguje.
class heap {
public:
void push(int);
int pop();
private:
vector<int> data;
};
void heap::push(int what) {
data.push_back(what);
int where = data.size() - 1;
while (where > 0) {
int parent = (where-1)/2;
if (data[where] > data[parent]) {
swap( data[where], data[parent] );
where = parent;
} else {
break;
}
}
}
int heap::pop() {
int n = data.size();
int answer = data[0];
swap( data[0], data[n-1] );
data.pop_back();
int where = 0;
while (true) {
int dest = where;
if (2*where+1 < n-1 && data[2*where+1] > data[dest])
dest = 2*where+1;
if (2*where+2 < n-1 && data[2*where+2] > data[dest])
dest = 2*where+2;
if (dest != where) {
swap( data[where], data[dest] );
where = dest;
} else {
return answer;
}
}
}