堆排序

来源:互联网 发布:网络推广平台又叫什么 编辑:程序博客网 时间:2024/05/16 08:49
#ifndef MAXHEAP_H_#define MAXHEAP_H_template<class T>class MaxHeap{public:MaxHeap(int mx = 10);virtual ~MaxHeap();bool IsEmpty();void Push(const T&);void Pop();const T& Top() const;  // Top就是查看根结点,private:T* heapArray;int maxSize;int currentSize;void trickleUp(int index);void trickleDown(int index);  // 向下渗透,};template<class T>MaxHeap<T>::MaxHeap(int mx = 10){if(mx < 1) throw "max size must >= 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;  // currentSize是用来计数的,}template<class T>void MaxHeap<T>::Push(const T& e){if(currentSize == maxSize) throw "MaxHeap is full.";heapArray[currentSize] = e;trickleUp(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];//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;   // leftChild 是下标,int rightChild = leftChild + 1;  // rightChild是下标,if(rightChild < currentSize && heapArray[leftChild] < heapArray[rightChild])largerChild = rightChild;else largerChild = leftChild;if(top >= heapArray[largerChild])break;heapArray[index] = heapArray[largerChild];index = largerChild;}heapArray[index] = top;}#endif

#include <iostream>#include "MaxHeap.h"using namespace std;int main(){MaxHeap<int> h(100);int arr[] = {12,31,3,6,2015};for(int i = 0; i < 5; ++i)h.Push(arr[i]);for(int i = 0; i < 5; ++i){arr[i] = h.Top();h.Pop();}for(int i = 0; i < 5; ++i)cout << arr[i] << " ";cout << endl;return 0;}

0 0
原创粉丝点击