diff --git a/堆排序 b/堆排序 new file mode 100644 index 0000000..79a9d5e --- /dev/null +++ b/堆排序 @@ -0,0 +1,66 @@ +//堆排序 +#include +#define N 1000 +#define INF 999999999 +int h[N]; +void heapAdjust(int n,int par) +{ + int tmp,pos,lc,rc; + while (par <= n/2) { + tmp = h[par]; + lc = par<<1; + rc = lc+1; + pos = par; + if (h[par] < h[lc]) { + h[par] = h[lc]; + pos = lc; + } + if (rc <= n && h[par] < h[rc]) { + h[par] = h[rc]; + pos = rc; + } + if (pos == par) + break; + else + h[pos] = tmp; + par = pos; + } +} +void createHeap(int n) +{ + int i; + + for (i = n/2; i != 0; i--) { + heapAdjust(n, i); + } +} +void heapSort(int n) +{ + int ntimes = n; + + while (ntimes--) { + printf("%d\n", h[1]); + h[1] = h[n]; + h[n--] = 0; + heapAdjust(n, 1); + } +} +int main(void) +{ + int n, i; + + scanf("%d", &n); + h[0] = INF; + for (i = 1; i != n+1; i++) { + scanf("%d", &h[i]); + } + createHeap(n); + heapSort(n); + return 0; +} +//参考测试数据 +6 +342 31 52 626 12 124 +10 +43 525 14 21 52 3 52 45 319 15155 +//原理:堆排序需要两个过程,一是建立堆,二是堆顶与堆的最后一个元素交换位置。所以堆排序有两个函数组成。一是建堆的渗透函数,二是反复调用渗透函数实现排序的函数 \ No newline at end of file