#ifndef _HEAP_H_
#define _HEAP_H_
using namespace std;
class heap
{
public:
heap()
{
}
int HeapPar(int i)
{
return i/2;
}
int HeapLeft(int i)
{
return 2*i;
}
int HeapRight(int i)
{
return 2*i+1;
}
template <class T>
int getArrayLen(T& array)
{//使用模板定义一个函数getArrayLen,该函数将返回数组array的长度
return (sizeof(array) / sizeof(array[0]));
}
void InHeat(int A[]);
void MaxHeapify(int i);
void BuildMapHeap();
int* Pheap;
int HeapSize;
~heap()
{
}
};
#endif
#include"heap.h"
void heap::BuildMapHeap()
{
for(int i=heap::HeapSize/2;i>=1;i--)
{
heap::MaxHeapify(i);
}
}
#include"heap.h"
void heap::InHeat(int A[])
{
// HeapSize=getArrayLen(A);
Pheap=A;
}
#include"heap.h"
void heap::MaxHeapify(int i)
{
int l,r,largest;
int temp;
l=HeapLeft(i);
r=HeapRight(i);
if((l<=HeapSize)&&(Pheap[l-1]>Pheap[i-1]))
{
largest=l;
}
else
{
largest=i;
}
if((r<=HeapSize)&&(Pheap[r-1]>Pheap[largest-1]))
{
largest=r;
}
if(largest!=i)
{
temp=Pheap[i-1];
Pheap[i-1]=Pheap[largest-1];
Pheap[largest-1]=temp;
heap::MaxHeapify(largest);
}
}
#include"heap.h"
#include<iostream>
using namespace std;
void HeapSort(heap& B)
{
B.BuildMapHeap();
int i;
int int_tem;
for(i=B.HeapSize;i>=2;i--)
{
int_tem=B.Pheap[0];
B.Pheap[0]=B.Pheap[i-1];
B.Pheap[i-1]=int_tem;
B.HeapSize--;
B.MaxHeapify(1);
}
}
#include<iostream>
#include"heap.h"
#include"heapsort.h"
using namespace std;
int main()
{
int arry[]={5,13,2,25,7,17,20,8,4};
int i=0;
cout<<"the original array:"<<endl;
for(;i<9;i++)
{
cout<<arry[i]<<" ";
}
cout<<endl;
heap B;
B.InHeat(arry);
B.HeapSize=9;
HeapSort(B);
cout<<"the sorted arry:"<<endl;
for(i=0;i<9;i++)
{
cout<<B.Pheap[i]<<" ";
}
cout<<endl;
return 0;
}
程序测试结果: