【用c 实现队列】用C++实现模板优先级队列及堆排序实例

更新时间:2019-09-23    来源:php应用    手机版     字体:

【www.bbyears.com--php应用】

模板优先级队列,数组实现,再熟悉一下常用算法,同时简单的堆排序应用

写了一个是队列自增长,另一个为了演示我还添加了一个叫做FillPq的方法,这个方法可以使用一个数组直接填充到优先级队列里,此时,优先级队列并不优先,然后进行下滤调整,之后建堆完成,输出即可

#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::FillPq( T arr[],int size )
{
N=size;
capacity=2*size;
for (int i=0;i {
pq[i+1]=arr[i];
}
}

template< class T>
PriorityQueue::PriorityQueue(void)
{
pq=new T[10];
N=0;
capacity=10;
}

template< class T>
void PriorityQueue::Insert( T x )
{
if (N==capacity)
{
Resize();
}
pq[++N]=x;
Swim(N);
}

template< class T>
T PriorityQueue::DelTop()
{
T max=pq[1];
Swap(1,N—);
Sink(1);
pq[N+1]=NULL;
return max;
}
//下滤
template< class T>
void PriorityQueue::Sink( int k )
{
while (2k<=N)
{
int j=2k;
if (j {
j++;
}
if (!Less(k,j))
{
break;
}
Swap(k,j);
k=j;
}
}
//上浮
template< class T>
void PriorityQueue::Swim( int k )
{
while (k>1 && Less(k/2,k))
{
Swap(k,k/2);
}
}

template< class T>
void PriorityQueue::Swap( int i,int j )
{
T temp=pq[i];
pq[i]=pq[j];
pq[j]=temp;
}

template< class T>
bool PriorityQueue::Less( int i,int j )
{
return pq[i] }

template< class T>
bool PriorityQueue::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::~PriorityQueue(void)
{
}

然后是堆排序

#include “stdafx.h”

include <iostream>
include
include “PriorityQueue.cpp”

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
PriorityQueue maxPq;

int arr[8]={1,2,4,3,6,8,7,5};
maxPq.FillPq(arr,8);
//建堆
for (int i=4;i>0;i--)
{
maxPq.Sink(i);
}
//输出
for (int i=1;i<=8;i++)
{
cout<<maxPq.DelTop();
}

}
 

iostream>

本文来源:http://www.bbyears.com/jiaocheng/68967.html

热门标签

更多>>

本类排行