1.代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define left(x) (2 * x + 1)
#define right(x) (2 * (x + 1))
void MaxHeapify(int* a, int i, int low, int high)
{
int l = left(i);
int r = right(i);
int largest;
int temp;
if (l <= high && a[l] > a[i]){
largest = l;
} else {
largest = i;
}
if (r <= high && a[r] > a[largest]){
largest = r;
}
if (largest != i){
temp = a[i];
a[i] = a[largest];
a[largest] = temp;
MaxHeapify(a, largest, low, high);
}
}
void BuildMaxHeap(int* a, int length)
{
for (int i = length / 2 - 1; i >= 0; i--){
MaxHeapify(a, i, 0, length - 1);
}
}
void HeapSort(int a[], int length)
{
int temp;
BuildMaxHeap(a, length);
for (int i = length - 1; i >= 1; i--){
temp = a[i];
a[i] = a[0];
a[0] = temp;
MaxHeapify(a, 0, 0, i - 1);
}
}
int main(int argc, char *argv[])
{
int array[10] = { 89, 4, 55, 1, 90, 100, 34, 22, 8, 21 };
HeapSort(array, 10);
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
system("pause");
return 0;
}
2.测试结果
