The priority Queue is a very important data structure. I used to use her when I was doing the ACM problem. C + + STL includes priority_queue . Java also has the Priorityqueue class. Unfortunately, priority queues are not included in the. NET Framework Base Class Library . So I had to write it myself in the C # language, as follows:
usingSystem;usingSystem.Collections.Generic;namespaceskyiv.util{classPriorityqueue<T> {IComparer<T> comparer; T[] Heap;public intCount {Get;Private Set; } PublicPriorityqueue (): This(NULL) { } PublicPriorityqueue (intcapacity): This(Capacity,NULL) { } PublicPriorityqueue (IComparer<T> comparer): This(comparer) { } PublicPriorityqueue (intCapacity,IComparer<T> comparer) { This. Comparer = (Comparer = =NULL) ?Comparer<t>. Default:comparer; This. heap =NewT[capacity]; }Public voidPush (T v) {if(Count >= heap.) Length)Array. Resize (refHeap, Count * 2); Heap[count] = v; Siftup (count++); } PublicT Pop () {varv = Top (); Heap[0] = Heap[--count];if(Count > 0) Siftdown (0);returnV } PublicT Top () {if(Count > 0)returnHEAP[0];throw NewInvalidOperationException("Priority queue is empty"); }voidSiftup (intN) {varv = heap[n]; for(varN2 = N/2; n > 0 && comparer.compare (V, heap[n2]) > 0; n = n2, N2/= 2) heap[n] = heap[n2]; Heap[n] = v; }voidSiftdown (intN) {varv = heap[n]; for(varN2 = n * 2; N2 < Count; n = n2, N2 *= 2) {if(n2 + 1 < Count && Comparer.compare (heap[n2 + 1], heap[n2]) > 0) n2++;if(Comparer.compare (V, heap[n2]) >= 0) Break; Heap[n] = heap[n2]; } Heap[n] = V; } }}
As shown above, this PriorityQueue<T>
generic class provides four public constructors, the first is a parameterless constructor, the rest of the constructors allow you to specify the initial number of elements (capacity) to include in the priority queue, and how to compare the keys (comparer).
This program uses the heap to implement the priority queue. Therefore, the space required is minimal. The time complexity of the Count property and the Top method is O (1), and the time complexity of the Push and Pop methods is O (Logn).
I've implemented a priority queue with the list<t> generic class, see my Blog Timus1016. A Cube on the Walk. Although simpler, the program code has only 23 lines, but the efficiency is not high, its Push and Pop method of the time complexity of O (N).
Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.
Implementing a priority queue in C #