n个数,找出其中最小的k个数。

直接上代码,其中有的c和c++混乱的地方,在vs2008下.cpp文件测试通过。

#include <stdio.h>
#include <stdlib.h>

//从节点cur开始向下成调整部分大根堆
//len为数组长度,数组下标从0开始
template<typename T>
void heap_adjust(T array[],int cur,int len)
{
	int l = cur*2+1;
	int r = l+1;
	int maxI = cur;
	T elem;

	if (l<len && array[l]>array[cur])
		maxI = l;
	if (r<len && array[r]>array[maxI])
		maxI = r;

	if (maxI!=cur)
	{
		elem = array[cur];
		array[cur] = array[maxI];
		array[maxI] = elem;
		heap_adjust(array,maxI,len);
	}
}

int main(void)
{
/* n个数找出其中最小的k个数 */
	printf("请输入k的值:\n");
	int k,count = 0,input_num;
	scanf("%d",&k);
	int *ptr_heap = (int*)malloc(k*sizeof(int));

	while (scanf("%d",&input_num) != EOF)
	{
		if (count<k)
		{
			ptr_heap[count++] = input_num;
			if (count==k)
			{
				//将长度为k的数组建立成大根堆
				for(int i=(k-1)/2;i>=0;i--)
					heap_adjust(ptr_heap,i,k);
			}
			continue;
		}

		//将input_num与大根堆的根(ptr_heap[0])作比较.
		//若小于根则留下input_num,同时用当前值input_num替换掉ptr_heap[0],然后调整堆;
		//反之读取下一个数据。
		if (input_num<ptr_heap[0])
		{
			ptr_heap[0] = input_num;
			heap_adjust(ptr_heap,0,k);
		}
		else
			continue;
	}
	for (int i=0;i<k;i++)
		printf(" %d",ptr_heap[i]);
	printf("\n");

	free(ptr_heap);
	ptr_heap = NULL;
	return 0;
}

 测试结果截图:

posted @ 2013-06-13 23:12  xiaowenchao  阅读(493)  评论(0编辑  收藏  举报