1 #include<iostream>
2 #include<algorithm>
3 #include<string>
4 #include<ctime>
5 #include<cmath>
6 #include<cassert>
7 using namespace std;
8 template<class T>
9 class MaxHeap{
10 private:
11 T*data;//数据元素
12 int count;//数量
13 int capacity;
14 //从结点start开始,自下向上比较调整
15 void shiftup(int start){
16 while(start>1&&data[start/2]<data[start]){
17 swap(data[start/2],data[start]);
18 start/=2;
19 }
20 }
21 void shiftdown(int k){
22 while(2*k<=count){//有孩子
23 int j=2*k; //在这轮循环中data[k]要和data[j]交换位置
24 if(j+1<=count&&data[j+1]>data[j]) j=k+1;
25 if(data[k]>=data[j]) break;
26 swap(data[k],data[j]);
27 k=j;
28 }
29 }
30 public:
31 MaxHeap(int capacity){//构造函数
32 data=new T[capacity+1];//因为数组在这里从1开始
33 count=0;
34 this->capacity=capacity;
35 }
36 ~MaxHeap(){delete []data;}//析构函数
37 //返回当前堆中的元素个数
38 int size(){return count;}
39 //判断是否为空
40 bool isEmpty(){return count==0;}
41 //插入item
42 void insert(T item){
43 assert(count+1<=capacity);
44 data[count+1]=item;//暂存
45 count++;
46 shiftup(count);
47 }
48 //取出并删去最大值(根)
49 T extractMax(){
50 assert(count>0);
51 T ret=data[1];
52 swap(data[1],data[count]);
53 count--;
54 shiftdown(1);
55 return ret;
56 }
57 //打印函数
58 void print(){
59 for(int i=1;i<=count;i++) cout<<data[i]<<endl;
60 }
61 };
62 //堆排序函数
63 template<class T>
64 void Heapsort(T arr[],int n){
65 MaxHeap<T>maxheap(n);
66 for(int i=0;i<n;i++) maxheap.insert(arr[i]);
67 //从小到大
68 for(int i=n-1;i>=0;i--) arr[i]=maxheap.extractMax();
69 }
70 int main(){
71 MaxHeap<int>maxheap(100);
72 cout<<maxheap.size()<<endl;
73 srand(time(NULL));
74 for(int i=0;i<15;i++) maxheap.insert(rand()%100);//0到100前闭后开的随机数
75 maxheap.print();
76 while(!maxheap.isEmpty()) cout<<maxheap.extractMax()<<" ";
77 cout<<endl;
78 return 0;
79 }