首页 > 编程语言 > 详细

堆排序C#版

时间:2016-02-25 13:26:22      阅读:140      评论:0      收藏:0      [点我收藏+]
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;
}
}
}

堆排序C#版

原文:http://www.cnblogs.com/Study02/p/5216517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!