c++ - While inserting nodes in heap how to use bubble up? -
following code doesnot bubbles larger value .can 1 out .the problem @ count++ .
#include<iostream> using namespace std; class heap{ public: int count; heap(int c) { count=c; } int arr[10]; void insert(int num); void deletemax(); void print(); }; void heap::insert(int num){ if(count==10){ cout<<"heap full\n"; exit(1); } else{ arr[count]=num; count++; //the real problem arises here compiler adds 1 count , when code moves ahead sets position var count++ value , tries compare value @ arr[pos] parent whereas there no value @ place set uptill. } int pos=count; while(arr[pos]>arr[(pos-1)/2]){ int temp; temp=arr[pos]; arr[(pos-1)/2]=temp; pos=(pos-1)/2; } } void heap::print(){ for(int i=0; i<10; i++){ cout<<arr[i]<<endl; } } int main(){ heap h(0); int a; int b=0; while(b<10){ cout<<"insert node in heap\n"; cin>>a; h.insert(a); b++; } h.print(); return 0; }
i agree, that's problem is.
Comments
Post a Comment