using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2016_2_25_HeapSort
{
class Program
{
static void Main(string[] args)
{
}
static void HeapAdjust(List<int> list,int parent,int length)
{
int temp=list[parent];//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;
}
public static List<int> HeapSort(List<int> list, int top)
{
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 >= list.Count - top; i--)
{
int temp = list[0];
list[0] = list[i];
list[i] = temp;
topNode.Add(temp);
HeapAdjust(list, 0, i);
}
return topNode;
}
}
}
原文:http://www.cnblogs.com/Study02/p/5216517.html