//数组抽象为堆排序
HeapSort.h
#pragma once
#include<stdio.h>
#include<assert.h>
typedef int SortDataType;
void HeapSort(SortDataType* a, int num);
void AdjustDown(SortDataType* a, int n, int size);
void Swap(SortDataType* a, SortDataType* b);
HeapSort.c
#include"heapsort.h"
//升序排列
//建大堆
void Swap(SortDataType* a, SortDataType* b)//多次交换
{
assert(a && b);
SortDataType mid = *a;
*a = *b;
*b = mid;
}
void AdjustDown(SortDataType* a, int n,int size)//向下建堆能用到,调整能用到
{
assert(a);
int parent = n;
int bigchild = n * 2 + 1;
while (bigchild < size)
{
if (bigchild+1<size&&a[bigchild] < a[bigchild + 1])
bigchild++;
if (a[bigchild] > a[parent])
{
Swap(a + bigchild, a + parent);
parent = bigchild;
bigchild = parent * 2 + 1;
}
else
break;
}
}
void HeapSort(SortDataType* a, int num)
{
assert(a&&num);
//向下建堆
for (int parent = (num - 1) / 2; parent >= 0; parent--)
{
AdjustDown(a, parent, num);
}
//调整,最大的调整至数组末尾,数组堆空间减1
while(num!=0)
{
Swap(a, a + num - 1);
AdjustDown(a, 0, --num);
}
}
main.c
#include"heapsort.h"
int main()
{
int arry[1];
for (int i = 0; i < 10; i++)
{
arry[i] = 10 - i;
}
HeapSort(arry, 10);
for (int i = 0; i < 10; i++)
{
printf("%d ", arry[i]);
}
printf("\n");
return 0;
}