Find the first k maximum number in the n number, the main use of small heap of characteristics, small heap, is the root node element is less than the left and right sub-tree elements, find the first K maximum number, first n number of the first number of K to generate a small heap, and then, in turn N in the remaining number of the root node of the small heap, if greater than the root node, the root node The heap is then generated in a small heap, and then until there is no surplus in N, the code is as follows
#define N 10000
#define K 100
void Create (int top[],int parent)
{
int child = 2 * parent + 1;
while (Child < K)
{
if (child + 1 < K && Top[child + 1] < Top[child])
{
child++;
}
if (Top[child]<top[parent])
{
Swap (Top[child], top[parent]);
parent = child;
Child = 2 * parent + 1;
}
Else
{
Break
}
}
}
void Greaterk (int a[])
{
ASSERT (K < N);
int top[k];
for (int i = 0; i < K; i++)
{
Top[i] = A[i];
}
Build a heap
for (int i = (K-2)/2; I >= 0; i--)
{
Create (Top,i);
}
Swap the top of the heap and the value greater than it
for (int i = K; i < N; i++)
{
if (Top[0] < a[i])
{
Top[0] = A[i];
Create (top, 0);
}
}
for (int i = 0; i < K; i++)
{
cout << Top[i] << "";
}
}
int main ()
{
int a[] = {3, 45, 2, 67, 4, 9, 1, 23, 6, 0};
Greaterk (a);
GetChar ();
return 0;
}
Find the top K maximum number in N number