TOP-K

#define _CRT_SECURE_NO_WARNINGS 1
#include 
#include 
//堆的向下调整
void swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void AdjustDown(int* p, int parent, int n)
{
	assert(p);
	int child = 2 * parent + 1;
	while (child < n)
	{
		if (child + 1 < n && p[child + 1] < p[child])
		{
			child++;
		}
		if (p[child] < p[parent])
		{
			swap(p + child, p + parent);
			parent = child;
			child = 2 * parent + 1;
		}
		else
		{
			break;
		}
	}
}
#define ALL 100000
#define HEAPSIZE 20
int main()
{
	//造大量数据
	int data[ALL];
	for (int i = 0; i < ALL; i++)
	{
		data[i] = i;
	}
	//建小根堆
	int heap[HEAPSIZE];
	for (int i = 0; i < HEAPSIZE; i++)
	{
		heap[i] = data[i];
	}
	for (int i = (HEAPSIZE - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(heap, i, HEAPSIZE);
	}
	//
	for (int i = 21; i < ALL; i++)
	{
		int num = data[i];
		if (num > heap[0])
		{
			heap[0] = num;
			AdjustDown(heap, 0, HEAPSIZE);
		}
	}
	//
	for (int i = 0; i < HEAPSIZE; i++)
	{
		printf("%d ",heap[i]);
	}
	return 0;
}

你可能感兴趣的:(算法,算法)