Code gone wrong

#include<bits/stdc++.h>
using namespace std;
#define ll long long
class heap{
vector v;
bool minheap;
bool compare(int a,int b)
{
if(minheap)
{
return a<b;
}
else
{
return a>b;
}

   }
   void heapify(int parent_index)
   {
       int left_index=2*parent_index;
       int right_index=2*parent_index+1;
       int min_index=parent_index;
       int last_index=v.size()-1;
       if(last_index>= left_index && compare(v[left_index],v[parent_index]) )
       {
           min_index=left_index;
       }
       if(last_index>= right_index && compare(v[right_index],v[parent_index]))
       {
           min_index=right_index;
       }
       while(min_index!=parent_index)
       {
          swap(v[min_index],v[parent_index]);
           heapify(min_index);
       }
   }
   public:
   heap(int default_size=10,bool type=true)
   {
       v.reserve(default_size);
       v.push_back(-1);
       minheap=true;
   }
   void push(int data)
   {
       v.push_back(data);
       int idx=v.size()-1;
       int parent=idx/2;
       if(idx>1 && compare(v[idx],v[parent]))
       {
              swap(v[idx],v[parent]);
              idx=parent;
              parent=parent/2;
       }
   }
   int top()
   {
       return v[1];
   }

   void pop()
   {
       int n=v.size()-1;
        swap(v[1],v[n]);
        v.pop_back();
        heapify(1);
   }
   bool empty()
   {
       return v.size()==1;
   }

};
int main()
{
//lets play
heap p;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int no;
cin>>no;
p.push(no);
}
while(!p.empty())
{
cout<<p.top()<<endl;
p.pop();
}
}

//
input given
1
1
2
3
4
5
output shown is
1

pleasee reply as ear;y as possible.

@sunneykumar309 compare right_index with min_index (and not parent_index)

give n=5 else program takes only 1 input!
if still facing problem, share saved code on ide.codingblocks.com

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.