#include "stdafx.h"
#define LeftChild(i) (2*(i)+1) //左子树坐标
void Swap(int *x,int *y)
{
int temp = 0;
temp = *x;
*x = *y;
*y = temp;
}
void PercDown(int A[], int i, int N) //i是堆的根节点
{
int child = 0;
while (LeftChild(i)<N) //非叶子节点
{
child = LeftChild(i);
if (child!=N-1 && A[child+1] > A[child])
child++;
if (A[i] < A[child])
Swap(&A[i],&A[child]);
else
break;
i=child;//下一轮跳到i的子树child,即往下跳一层
}
}
void HeapSort(int A[], int N)
{
int i = 0;
for (i=N/2-1; i>=0; i--)
PercDown(A,i,N);//创建堆
for (i=0; i<N-1; i++)
{
Swap(&A[0],&A[N-1-i]);
PercDown(A,0,N-i-1);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[] = {3,5,9,7,1,4,2,0,8,6};
int N = 10;
HeapSort(A,N);
return 0;
}
堆排序
最新推荐文章于 2024-06-03 19:59:27 发布