刚写的,还问题,回去看下怎么回事:
#include <cstdlib> #include "stdio.h" #define LeftChild(Index) (Index)<<1+1 #define RightChind(Index) (Index)<<1+2 void Adjust(int* aArray,int aIndex, int aLen) { int lCurIndex = aIndex; while(true) { const int lLeftChild = LeftChild(lCurIndex); if (lLeftChild > aLen) { return; } int lMaxIndex = lLeftChild; const int lRigthChild = RightChind(lCurIndex); if (lRigthChild < aLen && aArray[lLeftChild] < aArray[lRigthChild]) { lMaxIndex = lRigthChild; } if (aArray[lCurIndex] < aArray[lMaxIndex]) { int lTemp = aArray[lCurIndex]; aArray[lCurIndex] = aArray[lMaxIndex]; aArray[lMaxIndex] = lTemp; lCurIndex = lMaxIndex; } else { break; } } } void PrintArray(int* aArray, int aLen) { for (int i=0; i < aLen; ++i) { printf("%d ",aArray[i]); } printf(" "); } void Swap(int& a,int& b) { int temp = a; a = b; b = temp; } void HeapSort(int* aArray, int aLen) { for (int i = aLen/2; i >= 0; --i) { Adjust(aArray, i , aLen); } for (int i = aLen-1; i >0;--i) { Swap(aArray[0],aArray[i]); Adjust(aArray,1,i-1); } //PrintArray(aArray,aLen); } int main() { int lArry[100]; for (int i = 0; i < 100; ++i) { lArry[i] = i; } HeapSort(lArry,sizeof(lArry)/sizeof(int)); PrintArray(lArry,sizeof(lArry)/sizeof(int)); }