1.堆排序的实现:
如果要升序输出,则实现大堆
如果要降序输出,则实现小堆
逻辑:(升序输出)
将堆顶的元素和最后一个元素交换位置,此时左子树和右子树分别仍是大堆的顺序,交换位置后选出了最小的数。接着向下调整使剩余的元素再成为一个大堆,然后再交换,选出第二小的数…
代码:
Heap.h:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<time.h>
void Swap(int* p1, int* p2);
void AdjustDown(int* a, int n,int parent);
void AdjustUp(int* a, int child);
void HPSort(int* a, int n);
Heap.c:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include"Heap.h"void Swap(int* p1, int* p2)
{int tmp = *p1;*p1 = *p2;*p2 = tmp;
}
//向下调整:(建小堆)
void AdjustDown(int* a, int n,int parent)
{int child = 2 * parent + 1;while (child < n){if (child + 1 < n && a[child + 1] > a[child]){child = child + 1;}if (a[parent] < a[child]){Swap(&a[parent], &a[child]);parent = child;child = 2 * child + 1;}elsebreak;}
}
//向上调整:(建大堆)
void AdjustUp(int*a,int child)
{assert(a); int parent = (child - 1) / 2;while (child != parent){if (a[child] > a[parent]){Swap(&a[child], &a[parent]);child = parent;parent = (parent - 1) / 2;}elsebreak;}}//堆排序(升序):
void HPSort(int* a,int n)
{int end = n - 1;//建立大堆:for (int i = 1;i < n;i++){AdjustUp(a, i);}while (end > 0){Swap(&a[0], &a[end]);AdjustDown(a, end, 0);end--;}
}
2.TopK问题
将生成的一百万个随机数写入文件里面:
(Heap.h和Heap.c未改动)
#include"Heap.h"
//造数据:
void CreateData()
{int n = 1000000;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) % 10000000;fprintf(fin, "%d\n", x);}fclose(fin);
}
//打印最大的k个数:
void PrintTopk(const char* file, int k)
{FILE* fout = fopen(file, "r");if (fout == NULL){perror("fopen error");return;}int* minheap = (int*)malloc(sizeof(int) * k);int x = 0;for (int i = 0;i < k;i++){fscanf(fout, "%d", &minheap[i]);AdjustUp(minheap, i);}while (fscanf(fout, "%d", &x) != EOF){if (x > minheap[0]){minheap[0] = x;AdjustDown(minheap, k, 0);}}for (int i = 0;i < k;i++){printf("%d ", minheap[i]);}printf("\n");free(minheap);fclose(fout);
}
int main()
{CreateData();PrintTopk("data.txt", 5);return 0;
}