/* MinHeap.cpp */
template <class E>
MinHeap<E>::MinHeap(int sz){
maxHeapSize = (DefaultSize < sz)?sz:DefaultSize;
heap = new E[maxHeapSize];
if(heap == NULL){cerr<<"堆存储分配失败!"<<endl;exit(1);}
currentSize=0;
};
template <class E>//数组指针作为形参一般需要传递数组大小n,防止数组越界
MinHeap<E>::MinHeap(E arr[], int n){
maxHeapSize = (DefaultSize < n)?n:DefaultSize; //扩大数组上限为n
heap = new E[maxHeapSize];
if(heap == NULL){cerr<<"堆存储分配失败!"<< endl;exit(1);}
for(int i=0;i<n;i++) heap[i]=arr[i];
currentSize = n;
int currentPos =(currentSize-2)/2;
while(currentPos>=0){
siftDown(currentPos,currentSize-1);
currentPos--;
}
};
template <class E>
void MinHeap<E>::siftDown(int start, int m){
int i = start,j = 2*i+1;
E temp = heap[i];
while(j <= m){
if( j<m&&heap[j] > heap[j+1] ) j++;
if(temp <= heap[j]) break;
else {heap[i] = heap[j]; i=j;j=2*j+1;}
}
heap[i] = temp;
};
template <class E>
MinHeap<E>::MinHeap(int sz){
maxHeapSize = (DefaultSize < sz)?sz:DefaultSize;
heap = new E[maxHeapSize];
if(heap == NULL){cerr<<"堆存储分配失败!"<<endl;exit(1);}
currentSize=0;
};
template <class E>//数组指针作为形参一般需要传递数组大小n,防止数组越界
MinHeap<E>::MinHeap(E arr[], int n){
maxHeapSize = (DefaultSize < n)?n:DefaultSize; //扩大数组上限为n
heap = new E[maxHeapSize];
if(heap == NULL){cerr<<"堆存储分配失败!"<< endl;exit(1);}
for(int i=0;i<n;i++) heap[i]=arr[i];
currentSize = n;
int currentPos =(currentSize-2)/2;
while(currentPos>=0){
siftDown(currentPos,currentSize-1);
currentPos--;
}
};
template <class E>
void MinHeap<E>::siftDown(int start, int m){
int i = start,j = 2*i+1;
E temp = heap[i];
while(j <= m){
if( j<m&&heap[j] > heap[j+1] ) j++;
if(temp <= heap[j]) break;
else {heap[i] = heap[j]; i=j;j=2*j+1;}
}
heap[i] = temp;
};