# 【排序】--C语言实现堆排序

## 代码

#include <stdio.h>

/*

*/
void AdjustMaxHeap(int *a, int root, int last)
{
int i, child;
int tmp = a[root];
for (; 2 * root + 1 <= last; root = child) //循环到结点没有孩子结点为止
{
child = 2 * root + 1;
if (child + 1 <= last && a[child] < a[child + 1])  //先找出两个孩子结点中较大的一个
{
child++;
}
if (a[child] > a[root])  //如果孩子结点比较大，则和根节点交换
{
a[root] = a[child];
a[child] = tmp;
}
else
{
break;
}
}
}

void swap(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}

void HeapSort(int *a, int length)
{
//构建大顶堆
int i;
for (i = length / 2 - 1; i >= 0; i--)  //对于每棵子树都要调整
{
}

//调整大顶堆
for (i = length - 1; i > 0; i--)
{
swap(&a[0], &a[i]);
}
}

int main()
{
int i;
//int array[] = {4, 2, 7, 9, 0, 6, 2, 1, 8, 3};
int array[100000] = {0};
srand(time(NULL));
for (i = 0; i < 100000; i++)
{
array[i] = rand() % 1000 + 1;
}

HeapSort(array, sizeof(array) / sizeof(array[0]));

for (i = 0; i < sizeof(array) / sizeof(array[0]); i++)
{
printf("%d ", array[i]);
}
printf("\n");

return 0;
}



05-12
07-17

10-25
09-08 1万+
12-04
05-26 1694
12-12 1590