## 1.基本函数实现

### a.代码1(向下调整)

```void AdjustDown(DateType*a, int n, int parent)
{
int child = parent * 2 + 1;
while (child<n)
{
if ((child+1) < n && a[child] > a[child + 1])
{
++child;
}
if (a[parent] > a[child])
{
Swap(&a[parent], &a[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}```

### b.代码2(向上调整)

```void AdjustUp(DateType*a , int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}```

### c.代码3(交换）

```void Swap(DateType*p1, DateType*p2)
{
DateType tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}```

## 2.建堆

```void CreatHeap(Heap*p,DateType*num,int n)
{
assert(p);
p->a = (DateType*)malloc(n * sizeof(DateType));
if (p->a == NULL)
{
printf("malloc failed
");
exit(-1);
}
memcpy(p->a, num, n * sizeof(DateType));
p->size = n;
p->capacity = n;
//建小堆
for (int i = (n - 1 - 1) / 2; i >= 0; i--)
{
}
}```

## 3.插入数据

```void HeapPush(Heap*p, DateType x)
{
assert(p);
if (p->size == p->capacity)
{
DateType*tmp = (DateType*)realloc(p->a, (p->capacity) * 2 * sizeof(DateType));
if (tmp == NULL)
{
printf("realloc  failed
");
exit(-1);
}
}
(p->capacity) *= 2;
p->a[p->size] = x;
++(p->size);
//向上调整
}```

## 4. 删除数据

```void HeapPop(Heap*p, DateType x)
{
assert(p);
Swap(&p->a[0], &p->a[p->size-1]);
--(p->size);
//左右子树还是小堆，直接调整行了
}```

## 5.获取堆顶的数据

```DateType HeapTop(Heap*p)
{
assert(p);
return p->a[0];
}```

## 6.堆的数据个数

```int HeapSize(Heap*p)
{
assert(p);
return p->size;
}```

## 7.判空

```bool HeapIsEmpty(Heap*p)
{
assert(p);
return p->size == 0;
}```

## 8.打印

```void Print(Heap*p)
{
assert(p);
for (int i = 0; i < p->size; i++)
{
printf("%d ", (p->a)[i]);
}
printf("
");
int count = 0;//计数
int levelsize = 1;
for (int i = 0; i < p->size; i++)
{
printf("%d ", p->a[i]);
++count;
if (count == levelsize)
{
printf("
");
levelsize *= 2;
count = 0;//重新计数
}
}
printf("
");
}```

## 9.销毁

```void HeapDestory(Heap*p)
{
assert(p);
free(p->a);
p->a = NULL;
p->capacity = p->size = 0;
}```

## 10.测试

```int main()
{
int num[] = { 12,15,17,23,10,25 };
int n = sizeof(num) / sizeof(num[0]);
Heap a;
//创建小堆
CreatHeap(&a,num, n);
Print(&a);
printf("
");
//插入数据
HeapPush(&a, 1);
Print(&a);
//删除对顶的数据
HeapPop(&a);
Print(&a);
printf("
");
//获取堆顶数据
int ret=HeapTop(&a);
printf("The top date is %d
",ret);
//堆的数据个数
int number=HeapSize(&a);
printf("The number of heap is %d
", number);
//销毁
HeapDestory(&a);
return 0;
}```

## 12.用堆排序(降序)

a.代码1

```int main()
{
DateType num[] = { 12,15,17,23,10,25 };
int n = sizeof(num) / sizeof(num[0]);
HeapSort(num, n);
for (int i = 0; i < n; i++)
{
printf("%d ", num[i]);
}
printf("

");
return 0;
}
```
```void HeapSort(int*num, int n)
{
//建小堆
for (int i = (n - 1 - 1) / 2; i >= 0; i--)
{