Template priority queue, array implementation, familiar with common algorithms, and simple heap sorting application
I added a method named FillPq to demonstrate the self-growth of the queue. This method can be directly filled into the priority queue using an array. In this case, the priority queue is not given priority, next, perform the filter adjustment. After the heap is created, the output is enough.
# Include "stdafx. h"
Template <class T>
Class PriorityQueue
{
Private:
T * pq;
Int N;
Int capacity;
Public:
PriorityQueue (void );
~ PriorityQueue (void );
Void Insert (T x );
T DelTop ();
Void Swim (int k );
Void Sink (int k );
Bool Less (int I, int j );
Void Swap (int I, int j );
Bool Resize ();
Void FillPq (T arr [], int size );
};
Template <class T>
Void PriorityQueue <T>: FillPq (T arr [], int size)
{
N = size;
Capacity = 2 * size;
For (int I = 0; I <size; I ++)
{
Pq [I + 1] = arr [I];
}
}
Template <class T>
PriorityQueue <T >:: PriorityQueue (void)
{
Pq = new T [10];
N = 0;
Capacity = 10;
}
Template <class T>
Void PriorityQueue <T>: Insert (T x)
{
If (N = capacity)
{
Resize ();
}
Pq [++ N] = x;
Swim (N );
}
Template <class T>
T PriorityQueue <T>: DelTop ()
{
T max = pq [1];
Swap (1, N -);
Sink (1 );
Pq [N + 1] = NULL;
Return max;
}
// Downstream filter
Template <class T>
Void PriorityQueue <T>: Sink (int k)
{
While (2 k <= N)
{
Int j = 2 k;
If (j <N & Less (j, j + 1 ))
{
J ++;
}
If (! Less (k, j ))
{
Break;
}
Swap (k, j );
K = j;
}
}
// Floating
Template <class T>
Void PriorityQueue <T>: Swim (int k)
{
While (k> 1 & Less (k/2, k ))
{
Swap (k, k/2 );
}
}
Template <class T>
Void PriorityQueue <T>: Swap (int I, int j)
{
T temp = pq [I];
Pq [I] = pq [j];
Pq [j] = temp;
}
Template <class T>
Bool PriorityQueue <T>: Less (int I, int j)
{
Return pq [I] <pq [j];
}
Template <class T>
Bool PriorityQueue <T>: Resize ()
{
T newPq = new T [capacity2];
Capacity = capacity * 2;
For (int I = 1; I <= N; I ++)
{
NewPq [I] = pq [I];
}
Pq = newPq;
Return true;
}
Template <class T>
PriorityQueue <T> ::~ PriorityQueue (void)
{
}
Then the heap sorting
# Include "stdafx. h"
Include <iostream>
Include <string>
Include "PriorityQueue. cpp"
Using namespace std;
Int _ tmain (int argc, _ TCHAR * argv [])
{
PriorityQueue <int> maxPq;
Int arr [8] = {1, 2, 4, 3, 6, 8, 7, 5 };
MaxPq. FillPq (arr, 8 );
// Create a heap
For (int I = 4; I & gt; 0; I --)
{
MaxPq. Sink (I );
}
// Output
For (int I = 1; I & lt; = 8; I ++)
{
Cout & lt; maxPq. DelTop ();
}
}