最小堆排序
public class MinStack {
public int [ ] heap;
public int length;
public int left ( int i) {
return heap[ i<< 1 ] ;
}
public int right ( int i) {
return heap[ i<< 1 + 1 ] ;
}
public int parent ( int i) {
return heap[ i>> 1 ] ;
}
public int getLength ( ) {
return length;
}
}
public void insert ( int value) {
if ( length == heap. length) {
resize ( length<< 1 ) ;
}
++ length;
heap_decrease_key ( length- 1 , value) ;
}
public void heap_decrease_key ( int i, int value) {
heap[ i] = value;
while ( i >= 0 && heap[ i] < parent ( i) ) {
swap ( i, parent ( i) ) ;
i = parent ( i) ;
}
}
public int min_visitor ( ) {
if ( length == 0 ) {
return 0 ;
}
return heap[ 0 ] ;
}
public int min_pop ( ) {
if ( length == 0 ) {
return 0 ;
}
int res = heap[ 0 ] ;
heap[ 0 ] = heap[ length] ;
length-- ;
min_heapify ( 0 , getLength ( ) ) ;
return res;
}
public void min_heapify ( int i, int length) {
int le = left ( i) ;
int ri = righrt ( i) ;
int smallest = i;
if ( i < getLength ( ) && heap[ le] < heap[ i] ) {
smallest = le;
}
if ( i < getLength ( ) && heap[ ri] < heap[ i] ) {
smallest = ri;
}
if ( heap[ smallest] != heap[ i] ) {
swap ( smallest , i) ;
min_heapify ( smallest, length) ;
}
}
public void build_min_heap ( ) {
for ( int i= getLength ( ) / 2 ; i>= 0 ; i-- ) {
min_heapify ( i, getLength ( ) - 1 ) ;
}
}