# 【C语言】Top K问题【建小堆】

12 篇文章 0 订阅

## 前言

TopK问题：从n个数中，找出最大（或最小）的前k个数。

## 代码实现

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

// 造数据
void CreateNDate()
{
// 造数据
int n = 10000;
srand(time(0));
const char* file = "data.txt";
FILE* fin = fopen(file, "w");
if (fin == NULL)
{
perror("fopen error");
return;
}

for (int i = 0; i < n; ++i)
{
int x = (rand() + i) % 1000000;
fprintf(fin, "%d\n", x);
}

fclose(fin);
}
void Swap(int* px, int* py)
{
int tmp = *px;
*px = *py;
*py = tmp;
}
//向下调整算法
void AdjustDown(int* a, int n, int parent)
{
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && a[child + 1] < a[child])
{
child++;
}
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void PrintTopK(int k)
{
FILE* fout = fopen("data.txt", "r");
if (fout == NULL)
{
perror("fopen mail");
return;
}
int* minheap = (int*)malloc(sizeof(int) * k);
if (minheap == NULL)
{
perror("minheap mail");
return;
}
for (int i = 0; i < k; i++)
{
fscanf_s(fout, "%d", &minheap[i]);

}
//建小堆
for (int i = (k - 1 - 1) / 2; i >= 0; i--)
{
}
int x = 0;
int val = 0;
while (val = fscanf_s(fout, "%d", &x) != EOF)
{
if (x > minheap[0])
{
minheap[0] = x;
}
}
for (int i = 0; i < k; i++)
{
printf("%d ", minheap[i]);
}

fclose(fout);
}
int main()
{
//CreateNDate();
printf("请输入k：>");
int k = 0;
scanf_s("%d", &k);
PrintTopK(k);

return 0;
}


## 结果验证

• 37
点赞
• 18
收藏
觉得还不错? 一键收藏
• 24
评论
12-01 787
02-23 1747
09-15 2847
11-22 2186
06-01 950
09-20 1182
11-14 673
04-08 1232
09-05 435
09-06 659
09-04 389
09-04 411

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