# include <iostream>
# include <cassert>
using namespace std;
const int DefaultSize = 1 ;
template < class T , class E >
class MinHeap
{
public :
MinHeap ( int sz)
{
maxHeapSize = ( DefaultSize < sz) ? sz: DefaultSize;
heap = new E[ maxHeapSize+ 1 ] ;
if ( heap == NULL ) { cerr << "堆分配失败!" << endl; exit ( 1 ) ; }
currentSize = 0 ;
}
MinHeap ( E arr[ ] , int n)
{
maxHeapSize = ( DefaultSize < n) ? n: DefaultSize;
heap = new E[ maxHeapSize+ 1 ] ;
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-- ;
}
}
~ MinHeap ( ) {
delete [ ] heap;
}
bool Insert ( const E& x)
{
heap[ currentSize] = x;
siftUp ( currentSize) ;
currentSize++ ;
return true ;
}
bool RemoveMin ( E& x)
{
if ( currentSize == 0 ) return false ;
x = heap[ 0 ] ;
heap[ 0 ] = heap[ currentSize - 1 ] ;
currentSize-- ;
siftDown ( 0 , currentSize - 1 ) ;
return true ;
}
bool IsEmpty ( ) const {
return currentSize == 0 ;
}
bool IsFull ( ) const {
return currentSize == maxHeapSize;
}
void MakeEmpty ( ) {
delete heap;
currentSize = 0 ;
}
void output ( ) {
for ( int i = 0 ; i < currentSize; i++ )
cout << heap[ i] << " " ;
cout << endl;
}
private :
E * heap;
int currentSize;
int maxHeapSize;
void siftDown ( int start, int m)
{
int i = start, j= 2 * i+ 1 ;
T 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;
}
void siftUp ( int start)
{
int j = start, i= ( j- 1 ) / 2 ;
T temp= heap[ j] ;
while ( j > 0 )
{
if ( heap[ i] <= temp) break ;
else
{
heap[ j] = heap[ i] ;
j = i;
i = ( i - 1 ) / 2 ;
}
}
heap[ j] = temp;
}
} ;
# include <iostream>
using namespace std;
# include "min.h"
int main ( )
{
int a[ 5 ] = { 5 , 3 , 7 , 1 , 32 } ;
int x = 0 ;
MinHeap< int , int > mheap ( a, 5 ) ;
mheap. output ( ) ;
mheap. Insert ( 2 ) ;
mheap. RemoveMin ( x) ;
cout << "最小值: " << x<< endl;
mheap. output ( ) ;
return 0 ;
}