zoukankan      html  css  js  c++  java
  • 优先队列的实现

    优先队列的声明

    #ifmdef _BinHeap_H
    
    struct HeapStruct;
    typedef struct HeapStruct *PriorityQueue;
    
    PriorityQueue Initialize(int MaxElement);
    void Destory(PriorityQueue H);
    void MakwEmpty(PriorityQueue H)
    void Insert(ElementType X,PriorityQueue H);
    ElementType DeleteMin(PriorityQueue H);
    ElementType FindMin(PriorityQueue H);
    int IsEmpty(PriorityQueue H);
    int IsFull(PriorityQueue H);
    
    #endif
    
    struct HeapStruct
    {
    	int Capacity;
    	int Size;
    	ElementType *Elements;
    }
    

    优先队列的初始化

    PriorityQueue Initialize(int MaxElements)
    {
    	PriorityQueue H;
    	if(MaxElement < MinPQSize)
    		Error("Priority queue size is too small");
    	H = malloc(sizeof(struct HeapStruct));
    	if(H == NULL)
    		FatalError("Out of space!!!");
    	H->Elements = malloc((MaxElements + 1)*sizeof(ElementType));
    	if(H->Elements == NULL)
    		FatalError("Out of space!!!");
    	H->Capacity = MaxElements;
    	H->Size = 0;
    	H->Elements[0] = MinData;
    	
    	return H;
    }
    

    插入一个元素到二叉树中

    void Insert(ElementType X,PriorityQueue H)
    {
    	int i;
    	if(IsFull(H))
    	{
    		Error("Priority queue is full");
    		return 0;
    	}
    	for(i = ++H->Size;H->Elements[i/2] > X;i /= 2)
    		H->Elements[i] = H->Elements[i/2];
    	H->Elements[i] = X;
    }
    

    在二叉树中执行DeleteMin函数

    ElementType DeleteMin(PriorityQueue H)
    {
    	int i,Child;
    	ElementType MinElement,LastElement;
    	
    	if(IsEmpty(H))
    	{
    		Error("Priority queue is empty");
    		return H->Elements[0];
    	}
    	MinElement = H->Elements[1];
    	LastElement = H->Elements[H->Size--];
    	for(i = 1;i*2 <= H->Size;i = Child)
    	{
    		Child = i*2;
    		if(Child != H->Size && H->Elements[Child + 1] < H->Elements[Child])
    			Child ++;
    		if(LastElement > H->Elements[Child])
    			H->Elements[i] = H->Elements[Child];
    		else
    			break;
    	}
    	H->Elements[i] = LastElement;
    	return MinElement;
    }
  • 相关阅读:
    windows下mongodb的安装
    命令行执行大sql文件
    用css实现3D立方体旋转特效
    tp框架的详细介绍,tp框架基础
    用smarty来做简易留言系统,明细步骤简单操作
    怎么用php语言来做文件缓存
    用smarty模板做数据实现修改、分页等功能
    用smarty模板做的登录
    smarty函数
    Smarty变量
  • 原文地址:https://www.cnblogs.com/y3w3l/p/6369628.html
Copyright © 2011-2022 走看看