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

优先队列(堆) 数据结构与算法分析C语言实现

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

优先队列(堆) 数据结构与算法分析C语言实现

优先队列的声明
#ifndef _BinHeap_H

struct HeapStruct;
typedef struct HeapStruct *PriorityQueue;

PriorityQueue Initialize(int MaxElements);
void Destroy(PriorityQueue H);
void MakeEmpty(PriorityQueue H);
void Insert(int X, PriorityQueue H);
int DeleteMin(PriorityQueue H);
int FindMin(PriorityQueue H);
int IsEmpty(PriorityQueue H);
int IsFull(PriorityQueue H);

#endif

#define MinPQSize (5)
#define MinData (-10000)
struct HeapStruct
{
    int Capacity;
    int Size;
    int *Elements;
};
Initialize()
PriorityQueue Initialize(int MaxElements)
{
    PriorityQueue H;
    if (MaxElements < MinPQSize)
    {
        printf("Priority queue size is too small");
        exit(EXIT_FAILURE);
    }
    H = (PriorityQueue)malloc(sizeof(struct HeapStruct));
    if (H == NULL)
    {
        printf("Out of spacen");
        exit(EXIT_FAILURE);
    }
    H->Capacity = MaxElements;
    H->Size = 0;
    H->Elements = (int *)malloc(sizeof(int) * MaxElements + 1);
    if (H->Elements == NULL)
    {
        printf("Out of spacen");
        exit(EXIT_FAILURE);
    }
    H->Elements[0] = MinData;
    return H;
}
Destroy()
void Destroy(PriorityQueue H)
{
    if (H != NULL)
    {
        free(H->Elements);
        free(H);
    }
}
MakeEmpty()
void MakeEmpty(PriorityQueue H)
{
    H->Size = 0;
}
Insert()
void Insert(int X, PriorityQueue H)
{
    int i;
    if (IsFull(H))
    {
        printf("Priority queue is fulln");
        return;
    }
    for ( i = ++H->Size; H->Elements[i/2] > X; i /= 2)
        H->Elements[i] = H->Elements[i / 2];
    H->Elements[i] = X;
}
DeleteMin()
int DeleteMin(PriorityQueue H)
{
    int i, Child;
    int MinElement, LastElement;
    if (IsEmpty(H))
    {
        printf("Priority queue is emptyn");
        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]>H->Elements[Child+1])
            Child++;
        if (H->Elements[Child] < LastElement)
            H->Elements[i] = H->Elements[Child];
        else
            break;
    }
    H->Elements[i] = LastElement;
    return MinElement;
}
FindMin()
int FindMin(PriorityQueue H)
{
    return H->Elements[1];
}
IsEmpty()
int IsEmpty(PriorityQueue H)
{
    return H->Size == 0;
}
IsFull()
int IsFull(PriorityQueue H)
{
    return H->Size == H->Capacity;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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