一个简单的堆排序实现,以便自己以后查阅。
#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;
#define N 10000
int heapsize;
ifstream fin("input.txt");
void Heapsort(int *A);
void BuildMaxHeap(int *A);//建大顶推
void MaxHeapify(int *A, int i);
int main()
{
int A[N];
fin>>A[0];//存储元素个数
for(int i=1;i<=A[0];i++)
fin>>A[i];
Heapsort(A);
for(int i=1;i<=A[0];i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
void Heapsort(int *A)
{
heapsize=A[0];
BuildMaxHeap(A);
for(int i=heapsize ; i>=2; i--)//向下调整
{
swap(A[i],A[1]);
heapsize--;
MaxHeapify(A,1);
}
}
void BuildMaxHeap(int *A)//建大顶推
{
int i=A[0]/2;
for(; i>=1; i--)//向上调整
MaxHeapify(A,i);
}
void MaxHeapify(int *A, int i)
{
int l=i*2;
int r=l+1;
int largest;
if(l<=heapsize && A[l]>A[i])
largest=l;
else
largest=i;
if(r<=heapsize && A[r]>A[largest])
largest=r;
if(largest != i)
{
swap(A[largest], A[i]);
MaxHeapify(A,largest);
}
}