源代码
#include<iostream>
using namespace std;
template<class T>
void Swap(T& a,T&b){
T temp = a;
a = b;
b = temp;
}
template<class T>
class heap{
public:
heap(int n=10){
maxlength = n;
length = 0;
arr = new T[n];
}
~heap(){
delete []arr;
}
void insert(T&);
bool empty(){
return length == 0;
}
T& get(){
if(empty()){
cout<<"堆为空"<<endl;
}
return arr[0];
}
void del();
void output(){
for(int i=0;i<length;i++)cout<<arr[i]<<" ";
cout<<endl;
}
private:
T * arr;
int length;
int maxlength;
};
template<class T>
void heap<T>::del(){
if(empty()){
cout<<"堆为空"<<endl;
return ;
}
arr[0]=arr[--length];
int father = 0;
int child =1;
while(child<length){
if(child+1<length&&arr[child]<arr[child+1])child++;
if(arr[father]>=arr[child])break;
Swap(arr[father],arr[child]);
father = child;
child = (father<<1)+1;
}
}
template<class T>
void heap<T>::insert(T& element){
if(length==maxlength){
maxlength<<=1;
T* newArray = new T[maxlength];
for(int i=0;i<length;i++)newArray[i]=arr[i];
delete []arr;
arr = newArray;
}
arr[length]=element;
int child = length;
int father = (child-1)>>1;
while(father>=0){
if(arr[father]>=arr[child])break;
Swap(arr[father],arr[child]);
child = father;
father = (child-1)>>1;
}
length++;
}
int main(){
heap<int> h;
for(int i=0;i<10;i++)h.insert(i);
h.output();
h.del();
h.output();
}
输出结果
9 8 5 6 7 1 4 0 3 2
8 7 5 6 2 1 4 0 3