标签:堆应用
#pragma
#include<iostream>
#include<time.h>
#include<vector>
using namespace std;
//从十万个数中找出最大的前K个,用小堆
#define N 100000
#define K 100
vector<int> Data;
//产生海量数据
void GetData()
{
srand(unsigned(time(0)));
for (int i = 0; i < N; ++i)
{
Data.push_back(rand() % N + 1);//产生随机数在1到length间
}
}
void AdjustDown(int a[], int size, int parIndex)
{
int chiIndex = parIndex*2+1;
while (chiIndex < size)
{
if (chiIndex + 1 < size&&a[chiIndex + 1] < a[chiIndex])
++chiIndex;
if (a[chiIndex] < a[parIndex])
{
swap(a[chiIndex], a[parIndex]);
parIndex = chiIndex;
chiIndex = parIndex * 2 + 1;
}
else
break;
}
}
void GetTopK(vector<int>& Data)
{
int heapArray[K];
for (int i = 0; i < K; ++i)
{
heapArray[i] = Data[i];
}
//调整此堆为小堆
for (int i = (K - 1 - 1) / 2; i >= 0; --i)
{
AdjustDown(heapArray, K, i);
}
for (int i = K-1; i < N; ++i)
{
if (heapArray[0] < Data[i])
{
heapArray[0] = Data[i];
AdjustDown(heapArray, K, 0);
}
}
}
void Test1()
{
GetData();
GetTopK(Data);
}本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1752310
标签:堆应用
原文地址:http://10541556.blog.51cto.com/10531556/1752310