Hi all, i need help with this minheap code:
#include < vector>
using namespace std;
class heap {
vector <int> v;
public:
int hSize()
{
return v.size();
}
int rsize()
{
return hSize() - 1;
}
int parent(int i)
{
return (i - 1) / 2;
}
int left(int i)
{
return i * 2 + 1;
}
int right(int i)
{
return i * 2 + 2;
}
void swap(int i, int j)
{
int temp = v[j];
v[j] = v[i];
v[i] = temp;
}
void push(int e)
{
v.push_back(e);
int id = rsize();
if (hSize() > 1)
while (v[parent(id)] > v[id]) {
swap(parent(id), id);
id = parent(id);
}
}
int pop ()
{
int f = 0;
int p = v[0];
v[0] = v[rsize()];
if (hSize() > 1) {
while (v[left(f)] < v[f] || v[right(f)] < v[f]) {
if (v[left(f)] < v[f] && v[right(f)] < v[f]) {
if (v[left(f)] < v[right(f)]) {
swap(left(f), f);
f = left(f);
}
else {
swap(right(f), f);
f = right(f);
}
}
else {
if (v[left(f)] < v[f]){
swap(left(f), f);
f = left(f);
}
else {
swap(right(f), f);
f = right(f);
}
}
}
}
else { }
v.resize(rsize());
return p;
}
void show()
{
if (hSize() > 0) {
cout << "Heap content: ";
for (int i = 0; i < hSize(); i++) cout << v[i] << " ";
}
else cout << "\nHeap successfully emptied!";
cout << "\n";
}
bool Empty()
{
return v.empty();
}
~heap()
{
v.clear();
}
};
Well, the code does almost everything right, except when it pops the last element on the screen it prints a random number. What's your opinion?
Thanks!