1.堆的构建代码
#include<vector>
using namespace std;
template<class T>
class Heap
{
vector<T> vec;
int size;
void BuildHeap(void){
for(int i=size/2-1;i>=0;i--)
PercolateDown(i);
}
void PercolateDown(int h){
int p=h;
int c=2*p+1;
T temp=vec[p];
while(c<size)
{
if(vec[c]>vec[c+1]&&(c+1)<size)
c++;
if(vec[c]<temp)
{
vec[p]=vec[c];
p=c;
c=2*p+1;
}else{
break;
}
}
vec[p]=temp;
}
void PercolateUp(){
int c=size-1;
int p=(c-1)/2;
T temp=vec[c];
while(c>0)
{
if(vec[p]>temp)
{
vec[c]=vec[p];
c=p;
p=(c-1)/2;
}else
{
break;
}
}
vec[c]=temp;
}
public:
explicit Heap(int max=100):vec(max),size(0){
}
explicit Heap(const vector<T>& vt):vec(vt.size()+10),size(vt.size())
{
for(int i=0;i<size;i++)
{
vec[i]=vt[i];
}
BuildHeap();
}
bool Empty(void)const{return (size==0);}
int Size()
{
return size;
}
void Insert(const T& item){
if(size==vec.size())
{
vec.resize(vec.size()*2);
}
vec[size]=item;
size++;
PercolateUp();
}
const T& Top(void)const
{
return vec[0];
}
void DeleteMin(void){
if(size==0)
{
cout<<"MInHeap is Empty";
exit(1);
}
size--;
vec[0]=vec[size];
PercolateDown(0);
}
void DeleteMin(T& item){
if(size==0)
{
cout<<"MInHeap is Empty";
exit(1);
}
item=vec[0];
size--;
vec[0]=vec[size];
PercolateDown(0);
}
};
2.测试程序
#include<iostream>
#include<stdlib.h>
#include<vector>
#include"Heap12.h"
using namespace std;
int main()
{
vector<int> v;
int x;
for(int i=0;i<100;i++)
{
x= rand()%100;
v.push_back(x);
cout<<x<<"\n";
}
Heap<int> h(v);
/* for(int i=0;i<100;i++)
{
h.Insert(v[i]);
}*/
cout<<h.Size()<<"size\n";
v.clear();
while(!h.Empty())
{
h.DeleteMin(x);
cout<<x<<" ";
v.push_back(x);
}
return 0;
}
3.输出结果