創建最大(小)堆用於排序 實際上最大(小)堆是一隻平衡二叉樹 最大堆則任意父節點值大於子節點 最小堆反之 從小到大排序用最大堆 反之
排序原理是用堆頂與最右葉子結點互換 並斷開最右葉子節點 葉子節點輸出 整棵樹調整之後重複操作 直至結束
---C語言實現
---實現爲小堆排序
#include<stdio.h>
#include<stdlib.h>
//遍歷數組
void LoopForArr(int arr[],int length)
{
int count;
if(arr == NULL || length <=0)return ;
for(count = 0;count<length;count++)
{
printf("%d ",arr[count]);
}
printf("\n");
}
//建造堆(小)
void AjustHeap(int arr[],int Start,int End)
{
int count;
//調整
for(count = Start*2+1;count<=End;count = count*2+1)
{
if(Start*2+2<=End && arr[Start*2+2]<arr[count])
{
count = Start*2+2;
}
if(arr[count]<arr[Start])
{
arr[count]^=arr[Start]^=arr[count]^=arr[Start];
Start = count;
}
else
{
break;
}
}
}
//排序過程
void heapSort(int arr[],int length)
{
int count;
for(count = length-1;count>0;count--)
{
arr[0]^=arr[count]^=arr[0]^=arr[count];
AjustHeap(arr,0,count-1);
}
}
//堆排序 :小堆
void HeapSort(int arr[],int length)
{
int count;
if(arr == NULL || length <=0)return ;
//默認數組建樹完成 調整
for(count = length/2-1;count>=0;count--)
{
AjustHeap(arr,count,length-1);
}
//排序過程
heapSort(arr,length);
}
int main()
{
int arr[] = {22,34,1,6,9,123,55,78,12,4,56,87,52};
HeapSort(arr,sizeof(arr)/sizeof(arr[0]));
LoopForArr(arr,sizeof(arr)/sizeof(arr[0]));
system("pause");
return 0;
}