折腾大半天,终于弄明白啥是堆排序了,话不多说,安排。
首先要进行堆排序,需要一个堆(大顶堆/升序,小顶堆/降序,不知道堆是什么的自行百度),因此需要先建堆,以大顶堆(第一个元素下标为0)为例:
首先找到最后一个非叶子节点i=n/2-1,然后和它的叶子比较,如果叶子大于它,选最大的叶子交换位置,然后向前遍历其他的叶子节点重复此过程。
void siftDown(int arr[], int start, int end)//下滤操作
{
int root = start;
while (root * 2 + 1 <= end)
{
int child = root * 2 + 1;
int swap = root;
if (arr[swap] < arr[child])
swap = child;
if (child + 1 <= end && arr[swap] < arr[child + 1])
swap = child + 1;
if (swap != root)
{
int temp = arr[root];
arr[root] = arr[swap];
arr[swap] = temp;
root = swap;
}
else
break;
}
}
这里先找左子节点,然后找右子节点,如果没有交换,则停止该趟调整。
其实一开始不明白为什么在交换后不对其左右子树进行递归操作,来确保改变后其子树依旧保持大顶堆性质,后来想明白,改变的树的子树是符合性质的,如果改变,只需要考虑改变的节点对子树的影响,只需要改变比较的节点即可,即root = swap。
然后是对大顶堆进行排序,依次弹出第一个元素(最大值)即可,每次弹出后将最后一个节点放到对顶,再进行调整即可维护弹出后的堆,考虑到对剩余空间的利用,每次将弹出的节点与最后一个元素交换即可完成升序排序。
void heapSort(int arr[], int len)
{
for (int i = len / 2 - 1; i >= 0; i--)
{
siftDown(arr, i, len - 1);
}
for (int i = len - 1; i > 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
siftDown(arr, 0, i - 1);
}
}
完整程序如下(附测试程序):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void siftDown(int arr[], int start, int end)
{
int root = start;
while (root * 2 + 1 <= end)
{
int child = root * 2 + 1;
int swap = root;
if (arr[swap] < arr[child])
swap = child;
if (child + 1 <= end && arr[swap] < arr[child + 1])
swap = child + 1;
if (swap != root)
{
int temp = arr[root];
arr[root] = arr[swap];
arr[swap] = temp;
root = swap;
}
else
break;
}
}
void heapSort(int arr[], int len)
{
for (int i = len / 2 - 1; i >= 0; i--)
{
siftDown(arr, i, len - 1);
}
for (int i = len - 1; i > 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
siftDown(arr, 0, i - 1);
}
}
int main()
{
srand((unsigned)time(NULL));
int len = rand() % 10 + 10;
int *arr = (int *)malloc(len * sizeof(int));
for (int i = 0; i < len; i++)
arr[i] = rand() % 1024;
printf("排序前的数组:");
for (int i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
heapSort(arr, len);
printf("排序后的数组:");
for (int i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}