#include<iostream>
using namespace std;
void MaxHeap(int heap[],int i,int len)
{
int largeIndex = -1;
int left =i*2;
int right =2*i+1;
if(left <= len && heap[left]>heap[i]) //分开判断的巧妙之处在于可能右孩子不存在的情况
largeIndex = left;
else
largeIndex = i;
if (right <= len && heap[right]>heap[largeIndex])
largeIndex = right;
if(largeIndex != i)
{
swap(heap[i], heap[largeIndex]);
MaxHeap(heap, largeIndex, len);
}
}
void BuildHeap(int heap[], int len)
{
if(heap == NULL)
return ;
int index = len /2;
for(int i = index; i>=1;i--)
MaxHeap(heap,i,len);
}
int main()
{
int k;
int a[10]={1,2,3,4,5,6,7,8,9,10};
cin>>k;
int *heap=new int[k+1];
for(int i=1;i<=k;i++)
cin>>heap[i];
BuildHeap(heap,k);
for(i=0;i<10;i++)
{
if(a[i]< heap[1])
{
heap[1] = a[i];
MaxHeap(heap, 1,k);
}
}
for(int j=1;j<=k;j++)
cout<<heap[j]<<" ";
cout<<endl;
}
heap中取出k个最小值
最新推荐文章于 2021-08-10 00:16:20 发布