堆排序

#include <iostream>
using namespace std;
void Maxheapify(int A[],int i,int size){
	int left=2*i,right=2*i+1,largest;
	if (left<=size&&A[left]>A[i])
	{
		largest=left;
	} 
	else
	{
		largest=i;
	}
	if (right<=size&&A[right]>A[largest])
	{
		largest=right;
	} 
	if (largest!=i)
	{
		int temp=A[i];
        A[i]=A[largest];
		A[largest]=temp;
		Maxheapify(A,largest,size);
	}
}
void BuildMaxHeap(int A[],int n){
	int size=n;
	for (int i=n/2;i>=1;i--)
	{
		Maxheapify(A,i,size);
		
	}
}
void HeapSort(int A[],int n){
	BuildMaxHeap(A,n);
	int size=n;
	for (int j=n;j>=2;j--)
	{
		int temp=A[j];
		A[j]=A[1];
		A[1]=temp;
		size=size-1;
		Maxheapify(A,1,size);
	}
}
int main(){
	int A[11]={0,23,24,98,67,12,1,99,56,87,19};
        HeapSort(A,10);
	for (int i=1;i<=10;i++)
	{
		cout<<A[i]<<endl;
	}
	return 0;
}

posted @ 2012-05-07 21:18  应律  阅读(138)  评论(0编辑  收藏  举报