利用数组0位置作为守卫
#define LeftChild(i) (2*(i)+1) void PercDown(ElementType A[], int i, int N) { int child; ElementType tmp; for (tmp=A[i]; LeftChild(i)<N; i=child) { child = LeftChild(i); if (child != N-1 && A[child + 1]>A[child]) { child++; } if (tmp < A[child]) { A[i] = A[child]; } else break; } A[i] = tmp; } void Heapsort(ElementType A[], int N) { int i; for (i=N/2; i>=0; i++) { PercDown(A, N); } for (i=N-1; i>0; i--) { swap(&A[0], &A[i]); PercDown(A, 0, i); } }
原文:http://www.cnblogs.com/m2492565210/p/7257847.html