一、创建三个文件
二、代码实现
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;
}