The maximum heap is the big root heap -- the first n small and the smallest heap is the small root heap -- the first n Large, for example, the first n small, for the current element, compared with the heap top element (that is, the maximum heap value) of the Max heap, if it is smaller than the heap top element, the heap top element is replaced and the heap top element is adjusted. In this way, the minimum n elements can be obtained after scanning, which is very efficient. Problem example: Find the largest first 100 count in the number of million 1 INT_MIN initialize the minimum heap 2 read one count. If the number is greater than the heap top element, replace the heap top element and adjust the heap
// Base index 1
# Define LCHILD (I) (2 * (I ))
# Define RCHILD (I) (2 * (I) + 1)
Enum {
BIGHEAP = 0,
SMALLHEAP = 1,
};
// Adjust the heap
Template <typename T>
Void HeapAdjust (T * heap, size_t n, bool flg)
{
Int I = 1;
T root = heap [1];
While (I <n)
{
T ex;
If (flg = BIGHEAP) // maximum heap
{
If (LCHILD (I) <= n)
{
Ex = LCHILD (I );
If (RCHILD (I) <= n & heap [LCHILD (I)] Ex = RCHILD (I );
}
Else
Break;
If (heap [ex]> root)
{
Heap [I] = heap [ex];
I = ex;
}
Else
Break;
}
Else // minimum heap
{
If (LCHILD (I) <= n)
{
Ex = LCHILD (I );
If (RCHILD (I) <= n & heap [LCHILD (I)]> heap [RCHILD (I)])
Ex = RCHILD (I );
}
Else
Break;
If (heap [ex] <root)
{
Heap [I] = heap [ex];
I = ex;
}
Else
Break;
}
}
Heap [I] = root;
}
Void FindNNumber (const char * file, size_t n, bool flg)
{
Int * heap = new int [n + 1];
Int I;
For (I = 1; I <= n; I ++)
{
If (flg = BIGHEAP)
Heap [I] = INT_MAX;
Else
Heap [I] = INT_MIN;
}
FILE * fp = fopen (file, "r ");
Int;
While (fscanf (fp, "% d", & a)> 0)
{
If (flg = BIGHEAP)
{
If (a Heap [1] =;
}
Else
{
If (a> heap [1])
Heap [1] =;
}
HeapAdjust (heap, n, flg );
}
Fclose (fp );
For (I = 1; I <= n; I ++)
Printf ("% d \ n", heap [I]);
}
Void main ()
{
// Minimum n count
FindNNumber ("temp.txt", 10, BIGHEAP );
Printf ("\ n ");
// Maximum n count
FindNNumber ("tt.txt", 10, SMALLHEAP );
}