From 4876b1e7d1f9a0efe0a8770213d0c7b981244dce Mon Sep 17 00:00:00 2001 From: p7pykrxiq <1902838026@qq.com> Date: Fri, 18 Feb 2022 13:27:05 +0800 Subject: [PATCH] =?UTF-8?q?Add=20=E5=A0=86=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 堆排序 | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 堆排序 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