class MinHeap
{
private:
int heapSize;//堆大小
int *arr;//数组
public:
//构造函数
MinHeap(int length)//传入数组初始化大小
{
this->heapSize=length;
arr=new int[50];
}
//求父结点
int parent(int i)
{
return i/2;
}
//求左孩子
int left(int i)
{
return 2*i;
}
//求右孩子
int right(int i)
{
return 2*i+1;
}
//交换函数
void swap(int a,int b)
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
//维持堆性质函数,使用前提为左右子书均为最小堆
void heapIfy(int i,int localHeapSize)
{
int l=left(i);
int r=right(i);
int least=i;
//找出i,left(i),right(i)的最小值
if(l<=localHeapSize&&arr[least]>arr[l])
{
least=l;
}
if(r<=localHeapSize&&arr[least]>arr[r])
{
least=r;
}
//交换arr[i],arr[largest]
if(least!=i)
{
swap(i,least);
heapIfy(least,localHeapSize);
}
}
//初始化堆(建立堆)
void buildHeap()
{
for(int i=heapSize/2;i>=1;i--)
{
heapIfy(i,heapSize);
}
}
//堆排序算法(前提:堆已初始化)
void heapSort()
{
int localHeapSize=heapSize;
for(int i=heapSize;i>=2;i--)
{
swap(1,i);
--localHeapSize;
heapIfy(1,localHeapSize);
}
//倒置数组
int i=1;
int j=heapSize;
while(i<j)
{
swap(i,j);
++i;
--j;
}
}
//去掉并返回堆中最小的元素(前提:堆已初始化)
int extractMin()
{
if(heapSize>=1)
{
int min=arr[1];
swap(1,heapSize);
--heapSize;
heapIfy(1,heapSize);
return min;
}
else
{
cout<<"堆中没有元素"<<endl;
return -1;
}
}
//向堆中插入数据(前提:堆已经初始化)
void heapInsert(int key)
{
++heapSize;
int i=heapSize;
while(i>1&&arr[parent(i)]>key)
{
arr[i]=arr[parent(i)];
i=parent(i);
}
arr[i]=key;
}
//输入数组
void input()
{
int i=1;
while(i<=heapSize)
{
cin>>arr[i];
i++;
}
}
//输出数组
void display()
{
int i=1;
while(i<=heapSize)
{
cout<<arr[i]<<" ";
i++;
}
cout<<endl;
}
};
void main()
{
//测试数据:10,9,8,7,6,5,4,3,2,1
MinHeap test(10);//初始化的堆有10个元素
test.input();//输入数据
test.buildHeap();//初始化堆
test.display();//打印初始化堆
test.heapSort();//堆排序
test.display();//打印排序结果
test.buildHeap();//重新初始化堆
test.heapInsert(8);//将8插入堆中
test.display();//打印插入后结果
test.heapSort();//重新排序
test.display();//打印排序后结果
test.extractMin();//删除最小元素
test.display();//打印删除后结果
test.heapSort();//删除后再次排序
test.display();//输出删除后排序后结果
}