注:本文中所使用的堆的基本操作均在《堆的基本操作》中。
链接:https://blog.youkuaiyun.com/lw13572259173/article/details/84946167
优先级队列
定义
typedef int PQDataType;
typedef struct PriortQueue
{
Heap heap;
}PriortQueue, *pPriortQueue;
初始化
void InitPriortQueue(pPriortQueue pqueue)
{
assert(pqueue);
int arr[] = { 53, 17, 78, 9, 45, 65, 87, 23, 31 };
Initheap(&(pqueue->heap), arr, sizeof(arr) / sizeof(arr[0]),Less);
}
入队列
void PushPriortQueue(pPriortQueue pqueue, PQDataType d)
{
assert(pqueue);
//堆插入
Insertheap(&(pqueue->heap), d);
}
出队列
void PopPriortQueue(pPriortQueue pqueue)
{
assert(pqueue);
Romoveheap(&(pqueue->heap)); //堆删除
}
队头元素
int TopPriortQueue(pPriortQueue pqueue)
{
assert(pqueue);
return Topheap(&(pqueue->heap));//堆顶元素
}
元素个数
int SizePriortQueue(pPriortQueue pqueue)
{
assert(pqueue);
return Sizeheap(&(pqueue->heap));//堆元素个数
}
是否为空
int EmptyPriortQueue(pPriortQueue pqueue)
{
assert(pqueue);
return Emptyheap(&(pqueue->heap));//堆是否为空
}
100亿个数中找到最大前k个数
随机构造10000个数据,在其中找到其最大的前10个数据—小堆
1.获取前k个元素
2.用剩余元素与堆顶元素比较,大于堆定元素则替换,小于堆顶元素则下一个
void topk(pHeap heap, int* arr, int k)
{
assert(heap);
Initheap(heap, arr, k,Less);
Createheap(heap);
int i = k;
while (arr[i] > 0)
{
if (Topheap(heap) < arr[i])
{
Swap(&arr[i], &(heap->_hp[0]));
AdjustDown(heap, 0); //向下调整
}
i++;
}
}
堆排序
每一次都会将一个最大/最小的元素放到最后
void HeapAdust(int *arr, int size, int parent) //大堆 一次性只调整一个位置
{
int child = (parent << 1) + 1; //找到孩子
while (child && child <= size - 1)
{
//左右孩子中找最大的
if (child + 1 < size &&arr[child] < arr[child+1]) //右孩子存在且右孩子大于左孩子
{
child += 1;
}
//孩子大于双亲
if (arr[parent] < arr[child])
{
//交换
Swap(&arr[child], &arr[parent]);
//继续向下判断
parent = child;
child = (parent << 1) + 1;
}
else
return;
}
}
void heap(int* arr, int size)
{
//建堆
int root = ((size - 2) >> 1); //最后一个非叶子结点
int end = size - 1;
for (; root >= 0; root--) //构建一个大堆
HeapAdust(arr, size, root);
//删除——每一次最大的元素在堆顶,然后把最大元素与最后一个元素交换
while (end > 0)
{
Swap(&arr[0], &arr[end]);//交换堆顶与最后一个元素
HeapAdust(arr, end, 0); //只把end-1个元素再一次调整成堆 end相当于size
end--;
}
}
1万+

被折叠的 条评论
为什么被折叠?



