優先隊列(priority queue) 是很重要的數據結構
using System;
using System
namespace Skyiv
{
class PriorityQueue<T>
{
IComparer<T> comparer;
T[] heap;
public int Count { get; private set; }
public PriorityQueue() : this(null) { }
public PriorityQueue(int capacity) : this(capacity
public PriorityQueue(IComparer<T> comparer) : this(
public PriorityQueue(int capacity
{
this
this
}
public void Push(T v)
{
if (Count >= heap
heap[Count] = v;
SiftUp(Count++);
}
public T Pop()
{
var v = Top();
heap[
if (Count >
return v;
}
public T Top()
{
if (Count >
throw new InvalidOperationException(
}
void SiftUp(int n)
{
var v = heap[n];
for (var n
heap[n] = v;
}
void SiftDown(int n)
{
var v = heap[n];
for (var n
{
if (n
if (comparer
heap[n] = heap[n
}
heap[n] = v;
}
}
}
如上所示
泛型類提供四個公共構造函數
這個程序使用堆(heap)來實現優先隊列
我曾經用 List<T> 泛型類實現過一個優先隊列
From:http://tw.wingwit.com/Article/program/net/201311/15388.html