#include<iostream>
using namespace std;
typedef struct HeapStruct *MaxHeap;//最大堆
typedef struct HeapStruct *MinHeap;
#define MaxData 1000;
struct HeapStruct
{
int *Elements;
int size;
int Capacity;
};
MaxHeap Create(int MaxSize);//创建一个堆
bool IsFull(MaxHeap H);//判断是否满
bool Insert(MaxHeap H, int t);//插入元素
bool IsEmpty(MaxHeap H);//判断是否为空
int DelMax(MaxHeap H);//删除最大值
void LevelShow(MaxHeap H);//层次遍历
MaxHeap Create(int MaxSize)
{
MaxHeap H = new HeapStruct;
H->Elements = new int[MaxSize + 1];//加一是因为最大堆从1开始存放元素
H->size = 0;
H->Capacity = MaxSize;
H->Elements[0] = MaxData;
}
bool IsFull(MaxHeap H)
{
return(H->size == H->Capacity);
}
bool IsEmpty(MaxHeap H)
{
if (H->size == 0)
{
return true;
}
else
return false;
}
bool Insert(MaxHeap H, int t)
{
if (IsFull(H))
{
cout << "堆已满";
}
else
{
int i = ++H->size;
for (; H->Elements[i / 2] < t; i /= 2)//找到比t小的位置
H->Elements[i] = H->Elements[i / 2];
H->Elements[i] = t;
}
return true;
}
int DelMax(MaxHeap H)
{
int parent, child,Max,temp;
if (IsEmpty(H))
{
cout << "堆为空!";
}
else
{
Max = H->Elements[1];
temp = H->Elements[H->size--];
for (parent = 1; parent * 2 <= H->size; parent = child)
{
child = 2 * parent;
if (child != H->size&&H->Elements[child] < H->Elements[child + 1])
child++;
if (temp >= H->Elements[child])
break;
else
H->Elements[parent] = H->Elements[child];
}
H->Elements[parent] = H->Elements[child];
return Max;
}
}
void LevelShow(MaxHeap H)
{
int i;
for (i = 1; i < H->size; i++)
{
cout << H->Elements[i] << " ";
}
}
MinHeap CreateMin(int Maxsize)
{
MinHeap H = new HeapStruct;
H->Capacity = Maxsize;
H->Elements[0] = 0;//设定一个最小值当哨兵
H->size = 0;
return H;
}
void InsertMin(MinHeap H, int m)
{
if (IsFull(H))
{
cout << "erro";
}
else
{
int i = ++H->size;
for (; H->Elements[i / 2] > m; i /= 2)
H->Elements[i] = H->Elements[i / 2];
H->Elements[i] = m;
}
}
int Del(MinHeap H)
{
if (IsEmpty(H))
{
cout << "erro";
}
else
{
int Min = H->Elements[1];
int temp = H->Elements[H->size];
int parent, child;
for(parent = 1; 2 * parent <= H->size; parent = child)
{
child = 2 * parent;
if (H->Elements[child] > H->Elements[child + 1] && child != H->size)
child++;
if (H->Elements[child] >= temp)
break;
else
H->Elements[parent] = H->Elements[child];
}
H->Elements[parent] = temp;
return Min;
}
}
最大堆、最小堆 c++实现
最新推荐文章于 2024-03-26 23:29:24 发布