标签:
堆排序,这个上座率也比较高。
一般出现的问题是这样的,在 N 个数中找到前 K 个最大(小)的。
这种问题就是比较典型的大(小)顶堆,即堆顶的数值大于堆的孩子。
堆排序主要有建堆,或者叫做调整堆,及取堆顶。
一般在实现时采用树来实现,比如二叉树。
二叉树和数组有天然的映射关系,即数组中下标为 i 的左右子树分别为 2*i 及 2*i + 1。
不多说了,看代码,C# 实现的。
static void HeapAdjust(List<int> list, int parent, int length)
{
int temp = list[parent];
int child = 2 * parent + 1;
while (child < length)
{
if (child + 1 < length && list[child] < list[child + 1]) child++;
if (temp >= list[child])
break;
list[parent] = list[child];
parent = child;
child = 2 * parent + 1;
}
list[parent] = temp;
}
static List<int> HeapSort(List<int> list)
{
List<int> topNode = new List<int>();
for (int i = list.Count / 2 - 1; i >= 0; i--)
{
HeapAdjust(list, i, list.Count);
}
for (int i = list.Count - 1; i >= 0; i--)
{
int temp = list[0];
list[0] = list[i];
list[i] = temp;
topNode.Add(temp);
HeapAdjust(list, 0, i);
}
return topNode;
}
static void HeapSortTest()
{
List<int> lst = new List<int>() { 8, 4, 2, 5, 3, 0, 9, 1, 7, 6 };
var retlst = HeapSort(lst);
foreach (var item in lst)
{
Console.Write(item + ", ");
}
Console.Write("\n");
foreach (var item in retlst)
{
Console.Write(item + ", ");
}
Console.ReadKey();
}
这个排序返回的列表是逆序的。
传入的列表本身排序后是顺序的。
标签:
原文地址:http://my.oschina.net/xhan/blog/506773