源码
public static class Utilities
{
public static void Swap < T> ( ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
public enum Comparator { less = - 1 , equal = 0 , greater = 1 }
public class PriorityQueue< T> where T : IComparable
{
private int _size;
private int capacity;
private T[ ] elements;
private Comparator comparator;
public int size { get => _size; }
public bool empty { get => ( size == 0 ) ; }
public T top { get => elements[ 0 ] ; }
public PriorityQueue ( Comparator comparator = Comparator. less, int capacity = 1 )
{
_size = 0 ;
this . capacity = capacity;
this . comparator = comparator;
elements = new T [ capacity] ;
}
private void ShiftDown ( )
{
int cur = 0 ;
int child = 1 ;
while ( child < size)
{
if ( child + 1 < size && elements[ child + 1 ] . CompareTo ( elements[ child] ) == ( int ) comparator)
child++ ;
if ( elements[ child] . CompareTo ( elements[ cur] ) == ( int ) comparator)
{
Utilities. Swap < T> ( ref elements[ child] , ref elements[ cur] ) ;
cur = child;
child = 2 * cur + 1 ;
}
else break ;
}
}
private void ShiftUp ( )
{
int cur = size - 1 ;
int parent = ( cur - 1 ) / 2 ;
while ( cur > 0 )
{
if ( elements[ cur] . CompareTo ( elements[ parent] ) == ( int ) comparator)
{
Utilities. Swap < T> ( ref elements[ cur] , ref elements[ parent] ) ;
cur = parent;
parent = ( cur - 1 ) / 2 ;
}
else break ;
}
}
private void ExpandCapacity ( )
{
capacity = Mathf. CeilToInt ( capacity * 1.5f ) ;
T[ ] temp = new T [ capacity] ;
for ( int i = 0 ; i < size; i++ )
temp[ i] = elements[ i] ;
elements = temp;
}
public void Push ( T value )
{
if ( size == capacity)
ExpandCapacity ( ) ;
elements[ _size++ ] = value ;
ShiftUp ( ) ;
}
public void Pop ( )
{
if ( size == 0 )
return ;
Utilities. Swap < T> ( ref elements[ 0 ] , ref elements[ size - 1 ] ) ;
_size-- ;
ShiftDown ( ) ;
}
}
测试一
private void Start ( )
{
PriorityQueue< int > que = new PriorityQueue< int > ( ) ;
que. Push ( 5 ) ; que. Push ( 1 ) ; que. Push ( 3 ) ; que. Push ( 2 ) ; que. Push ( 8 ) ;
while ( ! que. empty)
{
Debug. Log ( que. top) ;
que. Pop ( ) ;
}
}
标题测试一结果
测试二
private void Start ( )
{
PriorityQueue< int > que = new PriorityQueue< int > ( Comparator. greater) ;
que. Push ( 5 ) ; que. Push ( 1 ) ; que. Push ( 3 ) ; que. Push ( 2 ) ; que. Push ( 8 ) ;
while ( ! que. empty)
{
Debug. Log ( que. top) ;
que. Pop ( ) ;
}
}
标题测试二结果