2022-04-09_建小堆实现Top-k问题

一、创建三个文件

​​​​​​​

 

二、代码实现

1.HeapTop_k.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include"HeapTop_k.h"


void PrintTopK(int* data, int n, int k)
{
	// 1.用data中前k个元素建堆
	int* kminHeap = (int*)malloc(sizeof(int) * k);
	assert(kminHeap);
	for (int i = 0; i < k; i++)
	{
		kminHeap[i] = data[i];
	}

	//建小堆
	for (int j = (k - 1 - 1) / 2; j >= 0; j--)
	{
		HeapAdjustDown(data, k, j);
	}

	// 2. 将剩余n-k个元素依次与堆顶元素比大小
	for (int i = k; i < n; i++)
	{
		if (data[i] > kminHeap[0])
		{
			kminHeap[0] = data[i];
			HeapAdjustDown(kminHeap, k, 0);
		}
	}
	for (int j = 0; j < k; j++)
	{
		printf("%d ", kminHeap[j]);
	}
	printf("\n");
}




void TestTopk()
{
	int n = 10000;
	int* data = (int*)malloc(sizeof(int) * n);
	srand(time(0));
	for (size_t i = 0; i < n; ++i)
	{
		data[i] = rand() % 1000000;
	}
	data[5] = 1000000 + 1;
	data[1231] = 1000000 + 2;
	data[531] = 1000000 + 3;
	data[5121] = 1000000 + 4;
	data[115] = 1000000 + 5;
	data[2335] = 1000000 + 6;
	data[9999] = 1000000 + 7;
	data[76] = 1000000 + 8;
	data[423] = 1000000 + 9;
	data[3144] = 1000000 + 10;
	PrintTopK(data, n, 10);
}

int main()
{
	TestTopk();         //测试用例
	return 0;
}

2.HeapTop_k.h

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>



//1.向下调整函数声明
void HeapAdjustDown(int* data, size_t size, size_t rootpos);


//2.交换数值函数实现
void Swap(int* pa, int* pb);

3.HeapTop_kFunc.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include"HeapTop_k.h"


//1.向下调整函数实现
void HeapAdjustDown(int* data, size_t size, size_t rootpos)
{
	size_t parentpos = rootpos;
	size_t childpos = parentpos * 2 + 1;
	while (childpos < size)
	{
		if (childpos + 1 < size && data[childpos + 1] < data[childpos])
		{
			childpos++;
		}

		if (data[childpos] < data[parentpos])
		{
			Swap(&data[childpos], &data[parentpos]);
			parentpos = childpos;
			childpos = parentpos * 2 + 1;
		}
		else
		{
			break;
		}
	}
}


//2.交换数值函数实现
void Swap(int* pa, int* pb)
{
	int tmp = 0;
	tmp = *pa;
	*pa = *pb;
	*pb = tmp;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值