堆排序
#include<cstdio>
#include<algorithm>
using namespace std;
inline int Parent(int i){return i>>1;}
inline int Left(int i){return i<<1;}
inline int Right(int i){return (i<<1) | 1; }
inline void Swap(int &a,int &b){if(a!=b) {a^=b;b^=a;a^=b;}}
//保持堆的性质
void MAXHeap(int *A,int heap_size,int i)
{
int l,r,max;
l = left(i);
r = Right(i);
if(l<=heap_size && A[l]>A[j])
max = l;
else max = i;
if(r<=heap_size && A[r]>A[max])
max = r;
if(max!=i)
{
Swap(A[i],A[max]);//就地排序
MAXHeap(A,heap_size,max);
}
}
建堆
void BuildMAXHeap(int* A,int heap_size)
{
for(int i = heap_size>>1;i>=1;--i)
MAXHeap(A,heap_size,i);
}
排序
void HeapSort(int* A,int heap_size)
{
BuildMAXHeap(A,heap_size);
int len = heap_size;
for(int i=heap_size;i>=2;--j)
{
Swap(A[1],A[i]);
--len;
MAXHeap(A,len,1);
}
}