#include <stdio.h>
#include <assert.h>
#include <windows.h>
void PrintArray(int* array, int size)
{
int i = 0;
for(; i < size; i++)
printf("%d ", array[i]);
printf("\n");
}
void Swap(int* pLeft, int* pRight)
{
int temp = 0;
assert(pLeft);
assert(pRight);
temp = *pLeft;
*pLeft = *pRight;
*pRight = temp;
}
void HeapAdjust(int* array, int parent, int size)//堆的调整,向下调整法,从最后一个非叶子节点
//开始调整
{
int child = parent*2 + 1;
while(child < size)
{
if(child+1 < size && array[child+1] > array[child])//如果右孩子存在且比左孩子大
child += 1;//让child标记右孩子
if(array[parent] < array[child])//双亲节点的值小于大孩子
{
Swap(&array[parent], &array[child]);//交换这两个节点的值,让双亲节点的值大于两个
//孩子的值
parent = child;//用parent标记child节点
child = parent*2 + 1;//找到新的child节点继续调整。因为没调整一个节点,就有可能打乱
//前面排好的序
}
else
return;
}
}
void HeapSort(int* array, int size)
{
int end = size - 1;
int root = ((size - 2)>>1);
for(; root >= 0; --root)//每调整完一个非节点,就调整紧挨着他的前边那个节点
HeapAdjust(array, root, size);//堆调整
while(end)//堆的删除:实际上是删除堆顶元素
{
Swap(&array[0], &array[end]);
HeapAdjust(array, 0, end);
--end;
}
}
void TestSort()
{
int array[] = {2, 5, 4, 9, 3, 6, 8, 7, 1, 0};
PrintArray(array, sizeof(array)/sizeof(array[0]));
HeapSort(array, sizeof(array)/sizeof(array[0]));
PrintArray(array, sizeof(array)/sizeof(array[0]));
}
int main()
{
TestSort();
system("pause");
return 0;
}