1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Diagnostics;
6: using System.Threading;
7:
8: namespace ConsoleApplication6
9: {
10: class Program
11: {
12: static void Main(string[] args)
13: {
14: List<int> list = new List<int>();
15:
16: //插入2w个数字
17: for (int i = 0; i < 100; i++)
18: {
19: Thread.Sleep(1);
20: list.Add(new Random((int)DateTime.Now.Ticks).Next(0, 100000));
21: }
22:
23: HeapSort(list);
24: Console.WriteLine("输出前十个数" + string.Join(",", list.Take(100).ToList()));
25:
26: Console.Read();
27:
28: }
29: /// <summary>
30: /// 堆排序主要通过类似于选出最大数来进行排序,先是通过函数将数据组合成为大根堆或者小根堆,确保父节点为最大的数或者最小的数,然后通过循环依次取出对应的最大的数或者最小的数放到索引的位置达到排序的效果。下面的函数主要的就是传递进来一个父节点,然后确保该节点在他的子节点中最大,然后通过循环确保后,将其替换
31: /// </summary>
32: /// <param name="list"></param>
33: /// <param name="parent"></param>
34: /// <param name="length"></param>
35: static void HeapAdjust(List<int> list, int parent, int length)
36: {
37: int temp = list[parent];
38: int child = parent * 2 + 1;
39: while (child < length)
40: {
41: if (child + 1 < length && list[child] < list[child + 1])
42: child++;
43: if (list[child] <= temp)
44: break;
45:
46: list[parent] = list[child];
47: parent = child;
48: child = parent * 2 + 1;
49: }
50: list[parent] = temp;
51: }
52:
53: public static void HeapSort(List<int> list)
54: {
55: for (int i = list.Count / 2 - 1; i >= 0; i--)
56: HeapAdjust(list, i, list.Count - 1);
57: for (int j = list.Count - 1; j >= 0; j--)
58: {
59: int temp = list[j];
60: list[j] = list[0];
61: list[0] = temp;
62:
63: HeapAdjust(list, 0, j);
64: }
65: }
66: }
67: }