heap是一种特殊的二叉树,始终将最大值或最小值留在二叉树根节点上,分别是MaxHeap和MinHeap实现 MinHeap与MaxHeap的实现区别在于大小比较相反 这里以MaxHeap实现为例,本场景下使用数组操作更方便,所以此处使用数组实现
public class MaxHeap {
private int capacity;
private int size = 1 ;
private int [ ] tree;
public MaxHeap ( int capacity) {
this . capacity = capacity;
this . tree = new int [ capacity] ;
}
public int poll ( ) {
if ( size- 1 == 0 ) throw new NoSuchElementException ( ) ;
int value = tree[ 1 ] ;
tree[ 1 ] = tree[ -- size] ;
int index = 1 , leftIndex = 2 , rightIndex = 3 ;
while ( rightIndex < size) {
if ( tree[ leftIndex] > tree[ rightIndex] ) {
swap ( leftIndex, index) ;
index = leftIndex;
} else {
swap ( rightIndex, index) ;
index = rightIndex;
}
leftIndex = index* 2 ;
rightIndex = index* 2 + 1 ;
}
if ( leftIndex < size) swap ( leftIndex, index) ;
return value;
}
public int peek ( ) {
if ( size- 1 == 0 ) throw new NoSuchElementException ( ) ;
return tree[ 1 ] ;
}
public void push ( int value) {
if ( size== capacity) {
capacity*= 2 ;
this . tree = Arrays . copyOf ( tree, capacity) ;
}
tree[ size++ ] = value;
riseUpMax ( ) ;
}
public void riseUpMax ( ) {
int index = size- 1 ;
while ( index != 1 ) {
int parentIndex = index/ 2 ;
if ( tree[ index] > tree[ parentIndex] ) {
swap ( index, parentIndex) ;
index = parentIndex;
} else break ;
}
}
public void swap ( int index1, int index2) {
int temp;
temp = tree[ index1] ;
tree[ index1] = tree[ index2] ;
tree[ index2] = temp;
}
@Override
public String toString ( ) {
StringBuilder sb = new StringBuilder ( "tree:\n" ) ;
int index = 1 ;
for ( int i = 1 ; i < size; i++ ) {
sb. append ( String . format ( "%-3d" , tree[ i] ) ) ;
if ( i== index) {
sb. append ( "\n" ) ;
index= index* 2 + 1 ;
}
}
return sb. toString ( ) ;
}
}