目录
- 什么是堆
- 堆的重要思想:向上调整法和向下调整法
- 建堆向上调整法和向下调整法谁更优
- 堆排序:排升序建大根堆还是小根堆
- 堆排序的延申问题:Top K问题
一、什么是堆
堆是一种特殊的完全二叉树,分为大堆和小堆,大堆:树中一个树及子树中,任何一个父亲都大于等于孩子;小堆:树中一个数及子树中,任何一个父亲都小于等于孩子;
结构如下(图片来自网络):
用数组实现堆:
typedef int HPDataType;
typedef struct Heap
{
HPDataType* _a;
int _size;
int _capacity;
}Heap;
二、堆的重要思想:向上调整法和向下调整法
a、堆的创建:
将第一个数看做堆,后面的数据依次加入堆,然后依次使用向上调整法,以下为一个建大根堆的步骤:
向上调整法代码实现:
//交换
void swap(HPDataType* a, HPDataType* b)
{
HPDataType tmp = *a;
*a = *b;
*b = tmp;
}
//向上调整法
void AdjustUp(int* a, int child)
{
int parent = (child - 1) / 2;
while (parent >= 0)//或则while(child > 0)
{
if (a[parent] < a[child])
{
swap(&a[parent], &a[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break; //当父节点大于等于子节点时也满足是一个大根堆了
}
}
}<