06.堆排序

1、概述:

  1. 堆排序(Heapsort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,
  2. 它是选择排序的一种。可以利用数组的特点快速定位指定索引的元素。
  3. 堆分为大根堆和小根堆,是完全二叉树。大根堆的要求是每个节点的值都不大于其父节点的值,
  4. 即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆,
  5. 因为根据大根堆的要求可知,最大的值一定在堆顶。

2、图解:

3、代码:

 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 }

 

原文地址:https://www.cnblogs.com/zhh19981104/p/9459116.html