C++實現大頂堆(插入,刪除)
阿新 • • 發佈:2019-02-22
turn 取出 arr temp public included code ++ ger
practice Max.h文件
#ifndef PRACTICE_MAX_H_INCLUDED #define PRACTICE_MAX_H_INCLUDED template <class T> class MaxHeap { public: MaxHeap(int mx=100); virtual ~MaxHeap(); bool IsEmpty(); void Push(const T& e); void Pop(); const T& Top() const; private: T* heapArray; int maxSize; int currentSize; void trickleUp(int index); void trickleDown(int index); }; template<class T> MaxHeap<T>::MaxHeap(int mx) { if(mx<1) throw"max size must be>1"; maxSize=mx; currentSize=0; heapArray=new T[maxSize]; } template<class T> MaxHeap<T>::~MaxHeap() { delete[] heapArray; } template<class T> bool MaxHeap<T>::IsEmpty() { return currentSize==0; } template<class T> void MaxHeap<T>::Push(const T& e) //插入一個值 { if(currentSize==maxSize) throw"MaxHeap is full"; heapArray[currentSize]=e; trickleUp(currentSize); currentSize++; } template <class T> void MaxHeap<T>::trickleUp(int index)//向上滲透? { int parent=(index-1)/2; T bottom=heapArray[index]; while(index>0&&heapArray[parent]<bottom) { heapArray[index]=heapArray[parent]; index=parent; parent=(parent-1)/2; } heapArray[index]=bottom; } template<class T> const T & MaxHeap<T>::Top() const//取出第一個值 { return heapArray[0]; } template <class T> void MaxHeap<T>::Pop() { heapArray[0]=heapArray[--currentSize]; trickleDown(0); } template<class T> void MaxHeap<T>::trickleDown(int index)//先下滲透 { int largerChild; T top=heapArray[index]; while(index<currentSize/2)//到了倒數第二層即可,因為已經可以操作最後一層了 { int leftChild=2*index+1; int rightChild=leftChild+1; if(rightChild<currentSize&&heapArray[leftChild]<heapArray[rightChild]) largerChild=rightChild;//如果存在右孩子且右孩子比左孩子大 else //右孩子不存在或者右孩子比左孩子小 largerChild=leftChild;//該index對應的左孩子一定存在,但是右孩子可能不存在 if(top>=heapArray[largerChild]) break; heapArray[index]=heapArray[largerChild]; index=largerChild; } heapArray[index]=top; } #endif // PRACTICE_MAX_H_INCLUDED
practice.cpp文件
#include<iostream> #include"practice Max.h" using namespace std; int main() { MaxHeap<int> h(100); // h.Push(20); // h.Push(30); // h.Push(40); h.Push(50); // h.Push(90); // cout<<h.Top()<<endl; // h.Pop(); // cout<<h.Top()<<endl; // h.Pop(); // cout<<h.Top()<<endl; // cout<<h.IsEmpty()<<endl; //堆排序 h.Push(50); h.Push(15); h.Push(30); h.Push(70); h.Push(6); cout<<h.Top()<<endl; h.Pop(); cout<<h.Top()<<endl; h.Pop(); cout<<h.Top()<<endl; h.Pop(); cout<<h.Top()<<endl; h.Pop(); cout<<h.Top()<<endl; h.Pop(); return 0; }
C++實現大頂堆(插入,刪除)