protected < E > void siftDown ( final List < E > elements , final int startIndex , final int endIndex ) { int rootIndex = startIndex ; while ( ( rootIndex * 2 + 1 ) <= endIndex ) { int swapIndex = rootIndex ; int leftChildIndex = ( rootIndex * 2 + 1 ) ; int rightChildIndex = ( leftChildIndex + 1 ) ; if ( getOrderBy ( ) . compare ( elements . get ( swapIndex ) , elements . get ( leftChildIndex ) ) < 0 ) { swapIndex = leftChildIndex ; } if ( rightChildIndex <= endIndex && getOrderBy ( ) . compare ( elements . get ( swapIndex ) , elements . get ( rightChildIndex ) ) < 0 ) { swapIndex = rightChildIndex ; } if ( swapIndex != rootIndex ) { swap ( elements , rootIndex , swapIndex ) ; rootIndex = swapIndex ; } else { return ; } } }
Creates a binary heap with the list of elements with the largest valued element at the root followed by the next largest valued elements as parents down to the leafs .