最大堆 yongmou

#ifndef MAXHEAP_H
#define MAXHEAP_H


template
<class T>
class MaxHeap{
T
* heap; //heap[1...]
int size;
int max_size;
public:
MaxHeap(
int max_size);
~MaxHeap(){ delete [] heap;}

public:
bool empty();//true if the heap is empty
bool full(); //true if the heap is full
T top(); //return the max element

bool insert(const T& item);
void deleteMax();//delete the max element
};

template
<class T>
MaxHeap
<T>::MaxHeap(int max_size){
heap
= new T[max_size+1];
this->max_size = max_size;
size
= 0;
}

template
<class T>
bool MaxHeap<T>::empty(){
return (size == 0);
}

template
<class T>
bool MaxHeap<T>::full(){
return (size == max_size);
}

template
<class T>
T MaxHeap
<T>::top(){
return heap[1];//heap[0]没有用
}

template
<class T>
bool MaxHeap<T>::insert(const T& item){
if(size == max_size)
return false;
int i;
size
++;
i
= size;
while((i != 1) && (item > heap[i/2])){
heap[i]
= heap[i/2];
i
/= 2;
}
heap[i]
= item;
}

template
<class T>
void MaxHeap<T>::deleteMax(){
if(size == 0)
return ;
int parent, child;
T tmp
= heap[size];
size
--;
parent
= 1;
child
= 2;
while(child <= size){
/* find the larger child of the current parent*/
if((child < size) && (heap[child] < heap[child+1]))
child
++;
if(tmp >= heap[child])
break;
/* move to the next lower level*/
heap[parent]
= heap[child];
parent
= child;
child
*= 2;
}
heap[parent]
= tmp;

}


#endif
原文地址:https://www.cnblogs.com/liyongmou/p/1781124.html