//#include "stdafx.h"
#include<iostream>
using namespace std;
int get_parent(int i)
{
return i>>1;
}
int get_lchild(int i)
{
return i<<1;
}
int get_rchild(int i)
{
return ((i<<1)+1);
}
void max_heapify(int A[],int i,int heapsize)
{
if(A==NULL || heapsize<0)
{
throw exception("Invalid Paramenters!");
}
int left=get_lchild(i);
int right=get_rchild(i);
int largest=i;
if(left<=heapsize && A[left]>A[i])
largest=left;
if(right<=heapsize && A[right]>A[largest])
largest=right;
if(largest!=i)
{
int temp=A[i];
A[i]=A[largest];
A[largest]=temp;
max_heapify(A,largest,heapsize);
}
}
void print_heap(int A[],int heapsize)
{
if(A==NULL ||heapsize<0)
throw exception("Invalid Parameters");
for(int i=1;i<=heapsize;i++)
cout<<A[i]<<" ";
cout<<endl;
}
void build_max_heap(int A[],int heapsize)
{
if(A==NULL ||heapsize<0)
throw exception("Invalid Parameters");
for(int i=heapsize >> 1;i>0;i--)
max_heapify(A,i,heapsize);
cout<<"建成的大根堆为:"<<endl;
print_heap(A,heapsize);
}
void heap_sort(int A[],int heapsize)
{
build_max_heap(A,heapsize);
for(int i=heapsize;i>0;i--)
{
int temp=A[1];
A[1]=A[i];
A[i]=temp;
max_heapify(A,1,i-1);
}
}
void main()
{
const int length=11;
int A[length]={0,4,1,3,2,16,9,10,14,8,7};
int heapsize=length-1;
heap_sort(A,heapsize);
cout<<"堆排序之后:"<<endl;
print_heap(A,heapsize);
}
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布