本节我没讲开始数据结构一大重要结构的学习,那就是树。
顾名思义二叉树每一层都是满的
1:顺序储存,使用数组
2:链式储存,使用链表
我们本节重点学习使用数组的表示方法,它还有一个名字叫做堆。
都知道堆是顺序储存,所以结构体和顺序表一样,一个表示大小,一个表示下标,动态申请空间
typedef int HPDataType;
typedef struct Heap
{
HPDataType* a;
int size;
int capacity;
}Heap;
我们让数组元素重新命名,让我们可以轻松修改元素的类型,方便其他时候使用。
//堆的初始化
void HeapInit(Heap* hp);
// 堆的销毁
void HeapDestory(Heap* hp);
// 堆的数据个数
int HeapSize(Heap* hp);
// 堆的判空
bool HPEmpty(Heap* hp);
void HeapInit(Heap* hp)
{
hp->a = NULL;
hp->capacity = hp->size = 0;
}
void HeapDestory(Heap* hp)
{
free(hp->a);
hp->a = NULL;;
hp->capacity = hp->size = 0;
}
int HeapSize(Heap* hp)
{
return hp->size;
}
bool HPEmpty(Heap* php)
{
assert(php);
return php->size == 0;
}
堆排序是一种非常重要的排序算法,我们先学堆排序的基础,向上调整和向下调整很重要!
void AdjustUp(HPDataType* arr,int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (arr[child] > arr[parent])
{
Swap(&arr[child], &arr[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
子节点和父节点的关系,向上调整算法,是子节点和父节点对比交换(交换函数自行定义),然后通过循环,互换子节点和父节点的位置,然后子节点和父节点向上移。
void AdjustDown(HPDataType* arr, int parent, int n)
{
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && arr[child] < arr[child + 1])
{
child++;
}
if (arr[child] > arr[parent])
{
Swap(&arr[child], &arr[parent]);
parent = child;
child = parent * 2 + 1;
}
else {
break;
}
}
}
我们需要把堆传递和需要调整的节点parent和堆的元素个数size传递过去。依然是通过子节点和父节点的比较进行调整。
void HeapPush(Heap* hp, HPDataType x)
{
assert(hp);
if (hp->capacity == hp->size)
{
int newcapcity = hp->capacity == 0 ? 4 : 2 * hp->capacity;
HPDataType* arr = (HPDataType*)realloc(hp->a,newcapcity * sizeof(HPDataType));
if (arr == NULL)
{
perror("realloc fail");
exit(1);
}
hp->a = arr;
hp->capacity = newcapcity;
hp->a[hp->size] = x;
AdjustUp(hp->a, hp->size);
}
}
void HeapPop(Heap* hp)
{
assert(!HPEmpty(hp));
Swap(&hp->a[0], &hp->a[hp->size - 1]);
--hp->size;
AdjustDown(hp->a, 0, hp->size);
}
HPDataType HeapTop(Heap* hp)
{
assert(!HPEmpty(hp));
return hp->a[0];
}
void HeapSort(int* a, int n)
{
for (int i = 0; i < n; i++)
{
AdjustUp(a, i);
}
int end = n - 1;
while (end > 0)
{
Swap(&a[0], &a[end]);
AdjustDown(a, 0, end);
end--;
}
}