int left(int i)
{
return 2*i;
}
int right(int i)
{
return 2*i+1;
}
void exchange(int &a,int &b)
{
a=a+b;
b=a-b;
a=a-b;
}
//--------------------------
template<typename T>
void max_heapify(T a[],int i,int size)
{
int l=left(i);
int r = right(i);
int largest = 0;
if(l<=size&&a[l]>a[i])
{
largest = l;
}
else
{
largest=i;
}
if(r<=size&&a[r]>a[largest])
{
largest=r;
}
if(largest!=i)
{
exchange(a[i],a[largest]);
max_heapify(a,largest,size);
}
}
//--------------------------
template<typename T>
void build_max_heap(T a[],int size)
{
for(int i=size/2;i>=1;--i)
{
max_heapify(a,i,size);
}
}
//--------------------------
template<typename T>
void heapsort(T a[],int size)
{
build_max_heap(a,size);
for(int i =size;i>=2;--i )
{
exchange(a[1],a[i]);
size=size-1;
max_heapify(a,1,size);
}
}
//----------------------例如----------------------
{
int data[]={0,8,5,4,6,13,7,1,9,12,11,3,10,2};//数组第一个元素不考虑
for(int i=1;i<14;i++)
{
printf("%d ",data[i]);
}
heapsort(data,13);
for(int i=1;i<14;i++)
{
printf("%d ",data[i]);
}
system("PAUSE");
return 0;
}
//--------------------------最小堆--只需要更改这个函数----------
template<typename T>
void max_heapify(T a[],int i,int size)
{
int l=left(i);
int r = right(i);
int largest = 0;
if(l<=size&&a[l]<a[i])
{
largest = l;
}
else
{
largest=i;
}
if(r<=size&&a[r]<a[largest])
{
largest=r;
}
if(largest!=i)
{
exchange(a[i],a[largest]);
max_heapify(a,largest,size);
}
}
//-----------------------------------
排序算法_堆排序(最大堆、最小堆)
最新推荐文章于 2023-12-28 21:03:24 发布