From e99e9c2200faa1226fb362a2ab6f70944e666d51 Mon Sep 17 00:00:00 2001 From: Manav888 <57567919+Manav888@users.noreply.github.com> Date: Sat, 29 Oct 2022 13:02:12 +0530 Subject: [PATCH] Add files via upload --- CPP DSA/Min_Heap.cpp | 110 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 CPP DSA/Min_Heap.cpp diff --git a/CPP DSA/Min_Heap.cpp b/CPP DSA/Min_Heap.cpp new file mode 100644 index 00000000..52bfaa54 --- /dev/null +++ b/CPP DSA/Min_Heap.cpp @@ -0,0 +1,110 @@ +#include +using namespace std; + +class MinHeap{ + public: + vector minHeap; + int heapSize; + int realSize=0; + + void resizeIt(int size){ + heapSize = size; + minHeap.resize(heapSize+1); + minHeap[0] = -1; + } + + int peek(){ + return minHeap[1]; + } + + void add(int element){ + realSize++; + + if(realSize>heapSize){ + cout<<"Added too many elements!"<minHeap[index] && index>1){ + swap(minHeap[parent], minHeap[index]); + index = parent; + parent = index/2; + } + } + + int pop(){ + + if(realSize<1){ + cout<<"Not enough element in the Heap!"; + return INT_MAX; + } else{ + int removed = minHeap[1]; + + minHeap[1] = minHeap[realSize]; + realSize--; + int index = 1; + + while(index<=realSize/2){ + int left = index*2; + int right = (index*2) + 1; + + if(minHeap[index]>minHeap[left] || minHeap[index]>minHeap[right]){ + if(minHeap[left]