小顶堆解决TopK问题
这里写自定义目录标题
问题
TopK问题
代码
#include <bits/stdc++.h>
#define N 10
#define K 4
using namespace std;
void HeapAdjust(int *heap,int k,int len)
{
heap[0] = heap[k];
for (int i= 2*k; i<=len; i*=2)
{
if(i<len&&heap[i]>heap[i+1])
{
i++;
}
if(heap[0]<=heap[i])
{
break;
}
else
{
heap[k]=heap[i];
k=i;
}
}
heap[k]=heap[0];
}
void HeapConstruct(int *heap)
{
for(int i=K/2; i>0; i--)
{
HeapAdjust(heap,i,K);
}
}
int main()
{
int h[N+1]= {0,1,5,3,6,2,7,2,14,5,26};
HeapConstruct(h);
for (int i=1; i<=K; i++)
{
printf("%d ",h[i]);
}
printf("\n");
for (int i=K; i<=N; i++)
{
if(h[i]<h[1])
{
i++;
}
else
{
h[1]=h[i];
HeapConstruct(h);
}
}
for (int i=1; i<=K; i++)
{
printf("%d ",h[i]);
}
return 0;
}