/*100w个数中找出最大的前K个数*/
从网站建设到定制行业解决方案,为提供成都网站设计、成都网站建设、外贸网站建设服务体系,各种行业企业客户提供网站建设解决方案,助力业务快速发展。创新互联将不断加快创新步伐,提供优质的建站服务。
#include <iostream>
using namespace std;
#include <assert.h>
const int N = 10000;
const int K = 100;
void AdjustDown(int topK[], int size, size_t parent)
{
assert(topK);
int child = parent*2 + 1;
while (child < size)
{
if (child+1 < size
&& topK[child+1] < topK[child])
{
++child;
}
if (topK[child] < topK[parent])
{
swap(topK[child], topK[parent]);
parent = child;
child = parent*2 + 1;
}
else
{
break;
}
}
}
void GetTopKValue(int array[], int topK[])
{
assert(K < N);
for (int i = 0; i < K; ++i)
{
topK[i] = array[i];
}
//建小堆
for (int i = (K-2)/2; i >= 0; --i)
{
AdjustDown(topK, K, i);
}
for (int i = K; i < N; ++i)
{
if (array[i] > topK[0])
{
topK[0] = array[i];
AdjustDown(topK, K, 0);
}
}
for (int i = 0; i < K; ++i)
{
cout<<topK[i]<<" ";
if (i%5 == 0)
{
cout<<endl;
}
}
cout<<endl;
}
void Test()
{
int array[N] = {0};
int topK[K] = {0};
for (int i = 0; i < N; ++i)
{
array[i] = i;
}
array[9] = 111111;
array[99] = 1111111;
array[999] = 11111111;
GetTopKValue(array, topK);
}
int main()
{
Test();
return 0;
}
文章题目:C++100w个数中找出最大的前K个数
文章出自:https://www.cdcxhl.com/article44/ghhhhe.html
成都网站建设公司_创新互联,为您提供云服务器、小程序开发、Google、网站排名、App设计、外贸建站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联