文章目录
- 一、先把这N个数的前K个建立一个小堆
- 二、再把这K个数与剩下的N-K个数进行比较交换
- 三、最后用向下调整算法就可以得到这N个数中最大的前K个
一、先把这N个数的前K个建立一个小堆
先创建一个文本文件,然后向里面写数据,这里N我设置的是1000
int n = 1000;
srand(time(0));
const char* file = "data.txt";
FILE* fin = fopen(file, "w");
if (fin == NULL)
{perror("fopen fail");return;
}for (size_t i = 0; i < n; i++)
{int x = rand() % 10000;fprintf(fin, "%d\n", x);
}
fclose(fin);int k = 5;FILE* fout = fopen(file, "r");if (fout == NULL){perror("fopen fail");return;}int* kminheap = (int*)malloc(sizeof(int) * k);if (kminheap == NULL){perror("kminheap malloc error");return;}for (int i = 0; i < k; i++){fscanf(fout, "%d", &kminheap[i]);}for (int i = (k - 1 - 1) / 2; i >= 0; i--){AdjustDown(kminheap, k, i);}
二、再把这K个数与剩下的N-K个数进行比较交换
int val = 0;
while (!feof(fout))
{fscanf(fout, "%d", &val);if (val > kminheap[0]){kminheap[0] = val;AdjustDown(kminheap, k, 0);}
}
三、最后用向下调整算法就可以得到这N个数中最大的前K个
void AdjustDown(HPDataType* a, int n, int parent)
{int child = parent + 1;while (child < n){if (child + 1 < n && a[child] < a[child + 1]){child++;}if(a[parent]>a[child])SwapHeap(&a[parent],&a[child]);parent = child;child = child * 2 + 1;}}
先赞后看,养成习惯!!!^ _ ^ ❤️ ❤️ ❤️
码字不易,大家的支持就是我坚持下去的动力。点赞后不要忘了关注我哦!
如有错误请您指正批评!