1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace 堆排序
8 {
9 class Program
10 {
11 /// <summary>
12 /// 堆排序
13 /// <para>调用:arry.HeapSort(arry.Length);</para>
14 /// </summary>
15 /// <param name="arry">待排序的数组</param>
16 /// <param name="top"></param>
17 public static void HeapSort(int[] arry, int top)
18 {
19 //List<int> topNode = new List<int>();
20
21 for (int i = arry.Length / 2 - 1; i >= 0; i--)
22 {
23 HeapAdjust(arry, i, arry.Length);
24 }
25
26 for (int i = arry.Length - 1; i >= arry.Length - top; i--)
27 {
28 int temp = arry[0];
29 arry[0] = arry[i];
30 arry[i] = temp;
31 HeapAdjust(arry, 0, i);
32 }
33 }
34
35 /// <summary>
36 /// 构建堆
37 /// </summary>
38 /// <param name="arry"></param>
39 /// <param name="parent"></param>
40 /// <param name="length"></param>
41 private static void HeapAdjust(int[] arry, int parent, int length)
42 {
43 int temp = arry[parent];
44
45 int child = 2 * parent + 1;
46
47 while (child < length)
48 {
49 if (child + 1 < length && arry[child] < arry[child + 1]) child++;
50
51 if (temp >= arry[child])
52 break;
53
54 arry[parent] = arry[child];
55
56 parent = child;
57
58 child = 2 * parent + 1;
59 }
60
61 arry[parent] = temp;
62 }
63 }
64 }