温故知新,基础复习(二叉堆排序)
最小堆(最终数组的数据是降序),最大堆(最终数组的数据是升序)
下例是最小堆
#include <stdio.h> #include <stdlib.h> void Swap(int Arra[],unsigned int LeftIndex,unsigned int RightIndex) { int TeampValue = Arra[LeftIndex]; Arra[LeftIndex]=Arra[RightIndex]; Arra[RightIndex]=TeampValue; } void MinHeapFixDown(int Arra[],unsigned int StartIndex,unsigned int ArraSize) { int TeampValue = Arra[StartIndex]; unsigned int MinValueIndexOfChild = 2*StartIndex+1; while(MinValueIndexOfChild<ArraSize) { //printf("%u,%d,%d,%d\n",StartIndex,TeampValue,MinValueIndexOfChild,ArraSize); if (MinValueIndexOfChild+1<ArraSize&&Arra[MinValueIndexOfChild]>Arra[MinValueIndexOfChild+1]) { MinValueIndexOfChild=MinValueIndexOfChild+1; } if (Arra[MinValueIndexOfChild]>=TeampValue) { break; } Arra[StartIndex]=Arra[MinValueIndexOfChild]; StartIndex=MinValueIndexOfChild; MinValueIndexOfChild=2*StartIndex+1; } Arra[StartIndex]=TeampValue; } void BuildMinHeap(int Arra[],unsigned int ArraSize) { if (ArraSize<2) { return; } //printf("build start\n"); for (unsigned int i = (ArraSize-1)/2+1; i >0; --i) { MinHeapFixDown(Arra,i-1,ArraSize); } //printf("build end\n"); } void HeapSort(int Arra[],unsigned int ArraSize) { BuildMinHeap(Arra,ArraSize); printf("ArraSize=%d\n",ArraSize); for (unsigned int i = ArraSize-1; i >=1; --i) { Swap(Arra,0,i); MinHeapFixDown(Arra,0,i); } } int main() { //int Arra[]={-6,-8,9,-3,-1,0,13,-15,28,-40}; int Arra[]={-6,10,-7,15,-9,12,50,-35,9}; HeapSort(Arra,sizeof(Arra)/sizeof(Arra[0])); for (int i = 0; i < sizeof(Arra)/sizeof(Arra[0]); ++i) { printf("%d,",Arra[i] ); } printf("\n"); }