diff --git a/heap.cpp b/heap.cpp new file mode 100644 index 0000000..bf7457c --- /dev/null +++ b/heap.cpp @@ -0,0 +1,81 @@ +#include +#include +using namespace std; +//Max heap +void upheapify(vector &heap,int idx){ + if(idx==0){ + return; + } + int parentidx=(idx-1)/2; + if(heap[parentidx] &heap,int idx){ + int leftidx=2*idx+1; + int rightidx=2*idx+2; + if(leftidx>=heap.size() && rightidx>=heap.size()){ + return; + } + int largestidx=idx; + if(leftidxheap[idx]){ + largestidx=leftidx; + } + if(rightidxheap[idx]){ + largestidx=rightidx; + } + if(largestidx==idx){ + return; + } + swap(heap[idx],heap[largestidx]); + downheapify(heap,largestidx); + +} +void buildheap(vector &heap){ + for(int i=0;i &heap){ + for(int i=heap.size()-1;i>=0;i--){ + downheapify(heap,i); + } +} +//delete peak element +void deletepeek(vector &heap){ + swap(heap[0],heap[heap.size()-1]); + heap.pop_back(); + downheapify(heap,0); +} + +void insert(vector &heap,int key){ + heap.push_back(key); + upheapify(heap,heap.size()-1); +} +void display(vector heap){ + for(int i=0;i heap; + int n; + cin>>n; + for(int i=0;i>x; + heap.push_back(x); +// insert(heap,x); + } + buildheapOptimised(heap); + display(heap); +// cout<