1.基础知识 2.过程分析 <1> void AdjustDwon(int* a, int n, int root) 向下调整算法分析: <2> void HeapSort(int* a, int n) 排序部分分析:
3.代码实现
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void Swap(int* p1, int* p2)
{
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void AdjustDwon(int* a, int n, int root)
{
int parent = root;
int child = parent*2+1;
while (child < n)
{
if (child + 1 < n && a[child] < a[child + 1])
{
child = child + 1;
}
if (a[child]>a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a, int n)
{
int i = 0;
for (i = (n - 2) / 2; i>=0; i--)
{
AdjustDwon(a, n, i);
}
int end = n - 1;
while (end>0)
{
Swap(&a[0], &a[end]);
AdjustDwon(a, end, 0);
--end;
}
}
void PrintArray(int* a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main()
{
int a[10] = { 5, 8, 2 , 1, 9, 4, 3, 7, 6, 0 };
int n = sizeof(a)/ sizeof(int);
HeapSort(a, n);
PrintArray(a, n);
return 0;
}
|