栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 实现优先队列的简单实例

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 实现优先队列的简单实例

C++ 实现优先队列的简单实例

优先队列类模版实现:

BuildMaxHeap.h头文件:

#include 
using namespace std; 
#define Left(i) i*2+1 
#define Right(i) i*2+2 
#define Parent(i) (i-1)/2 
void Max_Heapify(int a[],int length,int i) 
{ 
  int left,right; 
  left=Left(i); 
  right=Right(i); 
  int num=i; 
  if(lefta[i]) 
  { 
    num=left; 
  } 
  //此处逻辑判断出错,开始为else if,发现不能正确排序,改为else之后正确 
  if(righta[num]) 
  { 
    num=right; 
  } 
  if(num!=i) 
  { 
    int temp; 
    temp=a[i]; 
    a[i]=a[num]; 
    a[num]=temp; 
    Max_Heapify(a,length,num); 
  } 
} 
//此处添加利用循环方式代替递归Max_Heapify的函数,该函数可以替代Max_Heapify 
//在某些情况下能取得更好 的效果 
void Max_Heapify1(int a[],int length,int i) 
{ 
  int left,right,num=i,largest=i; 
  left=Left(i); 
  right=Right(i); 
  while(1) 
  { 
    if(a[left]>a[num]&&lefta[largest]&&right=0;i--) 
  { 
    Max_Heapify1(a,length,i); 
  } 
} 
 
void Heap_Sort(int a[],int length) 
{ 
  Build_Max_Heap(a,length); 
  int i; 
  int temp; 
  for(i=length-1;i>=1;i--) 
  { 
    temp=a[i]; 
    a[i]=a[0]; 
    a[0]=temp; 
    length-=1; 
    Max_Heapify1(a,length,0); 
  } 
} 

PriorQUeue.h

#include 
#include "BuileMaxHeap.h" 
using namespace std; 
#define MAX 100 
template class PriorQueue 
{ 
private: 
  int length; 
  type a[MAX]; 
public: 
PriorQueue () 
{ 
  int i; 
  length=0; 
   
  for(i=0;ivoid PriorQueue::Init(type b[],int len) 
{ 
  int i; 
  this->length=len; 
  if(len<=0) 
  { 
    cout<<"Init failed !"<void PriorQueue::BuildMaxHeapQueue() 
{ 
  Build_Max_Heap(a,length); 
} 
templatetype PriorQueue::Maxnum() 
{ 
  if(length<=0) 
  { 
    cout<<"the queue is empty!"<bool PriorQueue::DeleteMax() 
{ 
  if(length<=0) 
  { 
    cout<<"the queue is empty!"<void PriorQueue::IncreaseKey(int i,type key) 
{ 
  int num=i; 
  if(key0&&a[Parent(num)]void PriorQueue::Insert(type key) 
{ 
  if(length>=MAX) 
  { 
    cout<<"the queue is full can't add more!"<void PriorQueue::Print() 
{ 
  int i; 
  for(i=0;i::Sort() 
{ 
  Heap_Sort(a,length); 
} 
 

main.cpp

#include"PriorQueue.h" 
#include 
using namespace std; 
 
int main() 
{ 
  PriorQueue node; 
  int b[10]={4,1,3,2,16,9,10,14,8,7}; 
  node.Init(b,10); 
  int i; 
  node.Print(); 
  cout<

以上就是数据结构优先队列的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/63291.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号