//topK.h
#pragma once
#include <iostream>
#include <assert.h>
#include <time.h>
#define K 10
#define N 100000
using namespace std;
//向下调整(最小堆)
template<class T>
void Adjustdown(T* top, size_t root)
{
assert(root < K);
size_t parent = root;
size_t child = 2 * parent + 1;
while (parent < K)
{
//右孩子存在且小于K且右孩子小于左孩子
if (child + 1 < K && top[child + 1] < top[child])
child++;//将child指向更小的结点
//当前较小孩子小于父节点时交换,并下滤
if (child < K && top[child] < top[parent])
{
std::swap(top[child], top[parent]);
parent = child;
child = child << 1 + 1;
}
else
break;
}
}
template<class T>
void topK(T *arr, T *top)
{
assert(K < N);
//将top数组存储满
for (size_t i = 0; i < K; ++i)
{
top[i] = arr[i];
}
//下调
for (int j = (K - 2) >> 1; j >= 0; --j)
{
Adjustdown(top, j);
}
for (size_t k = K; k < N; ++k)
{
if (top[0] < arr[k])//堆顶小于新比较的元素交换
{
std::swap(top[0], arr[k]);
Adjustdown(top, 0);//调整最小堆的结构
}
}
//遍历完成,top数据内存储的就是最大的前K个数
for (size_t idx = 0; idx < K; ++idx)
{
cout << top[idx] << " ";
}
cout << endl;
}
template<class T>
void topK(T *arr, T *top)
{
assert(K < N);
//将top数组存储满
for (size_t i = 0; i < K; ++i)
{
top[i] = arr[i];
}
//下调
for (int j = (K - 2) >> 1; j >= 0; --j)
{
Adjustdown(top, j);
}
for (size_t k = K; k < N; ++k)
{
if (top[0] < arr[k])//堆顶小于新比较的元素交换
{
std::swap(top[0], arr[k]);
Adjustdown(top, 0);//调整最小堆的结构
}
}
//遍历完成,top数据内存储的就是最大的前K个数
for (size_t idx = 0; idx < K; ++idx)
{
cout << top[idx] << " ";
}
cout << endl;
}
//test.cpp
#include "topk.h"
void Test()
{
int arr[N] = { 0 };
int top[K] = { 0 };
srand((unsigned)time(0));//随机种子
for (size_t idx = 0; idx < N; ++idx)
{
arr[idx] = rand()%1234;
}
topK(arr, top);
}
int main()
{
Test();
system("pause");
return 0;
}
2018-10-24 topK问题代码
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 2018.2.3 目标:身心健康,财富丰盛 好种子: 1早起健康早餐,种下健康的种子,回向群里姐妹及家人身心健康 ...
- 因为兴奋了一个晚上,第二天我就由着性子睡到自然醒。醒来,我们一伙备齐了相应的物品就直奔离共和县城最近的一家寺院——...