#include<iostream>
#include<string>
#include<vector>
#include<string.h>
#include<Windows.h>
using namespace std;
class heap
{ private:
int *v;
int heap_size;
public:
heap() {}
heap(int size)
{ heap_size=size;
v=new int[10*size] ;
v[0]=0;//标志位
cout<<"please input Array element:"<<endl;
for(int i=1;i<=size;++i)
cin>>v[i];
}
void build_max_heap();//创建最大堆
void max_heapify(int i);//保持最大堆的性质
void heapsort();//堆排序
int heap_maxnum();//返回堆中最大值
int heap_extramax();//返回堆的最大值并删除
void heap_increase_key(int i,int key);//修改堆中i位置的元素的值
void max_heap_insert(int key);//在堆中插入一个元素
void output();//输出堆中的元素
~heap()
{delete []v;}
};
void heap::max_heapify(int i)
{ int n=heap::heap_size;
int l=i<<1,r=(i<<1)+1,largest=i;
if(l<=n&&v[l]>v[largest]) largest=l;
if(r<=n&&v[r]>v[largest]) largest=r;
if(largest!=i)
{int temp=v[i];
v[i]=v[largest];
v[largest]=temp;
max_heapify(largest);
}
}
void heap::build_max_heap()
{ int n=heap::heap_size;
for(int i=n/2;i>0;--i)
max_heapify(i);
}
void heap::heapsort()
{ build_max_heap();
int n=heap::heap_size;
for(int i=n;i>1;--i)
{ int temp=v[i];
v[i]=v[1];
v[1]=temp;
heap::heap_size--;
max_heapify(1);
}
for(int i=0;i<=n;++i)
cout<<v[i]<<" ";
cout<<endl;
}
int heap::heap_maxnum()
{ build_max_heap();
return v[1];
}
int heap::heap_extramax()
{ int n=heap::heap_size;
int max=v[1];
v[1]=v[n];
heap::heap_size--;
max_heapify(1);
return max;
}
void heap::heap_increase_key(int i,int key)
{ if(v[i]>key)
{ v[i]=key;
max_heapify(i);
}
else {
v[i]=key;
while(i>1&&v[i/2]<v[i])
{ int temp=v[i];
v[i]=v[i/2];
v[i/2]=temp;
i=i/2;
}
}
}
void heap::max_heap_insert(int key)
{
heap::heap_size++;
int n=heap::heap_size;
v[n]=-0xffff;
heap_increase_key(n,key);
}
void heap::output()
{ int n=heap::heap_size;
for(int i=0;i<=n;++i)
cout<<v[i]<<" ";
cout<<endl;
}
int main()
{ system("color 1C");
heap s(10);
cout<<"bulit_maxheap:"<<endl;
s.build_max_heap();
cout<<"output the heap: ";
s.output();
cout<<"please output the heap maxnum: ";
cout<<s.heap_maxnum()<<endl;
cout<<"please output the heap maxum and delete it: ";
cout<<s.heap_extramax()<<endl;
cout<<"output the heap: ";
s.output();
cout<<"please input a key to insert the heap : ";
int key;
cin>>key;
s.max_heap_insert(key);
cout<<"output the heap: ";
s.output();
cout<<"plese input a position and a key : ";
int i;
cin>>i>>key;
s.heap_increase_key(i,key);
cout<<"output the heap: ";
s.output();
cout<<"the heap after sort:";
s.heapsort();
return 0;
}
输出结果: