Heap Sort

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sort
{
    /// 
    /// http://en.wikipedia.org/wiki/Heapsort
    /// 
    class HeapSort1
    {
        public HeapSort1()
        {
            Console.WriteLine("===============================================");
            Console.WriteLine("O(n log n)");

        }
        /// 
        /// 小根堆排序
        /// 
        /// 
        /// 
        /// 
 
 

        private static void HeapSort(ref double[] dblArray)
        {
            for (int i = dblArray.Length - 1; i >= 0; i--)
            {
                if (2 * i + 1 < dblArray.Length)
                {
                    int MinChildrenIndex = 2 * i + 1;
                    //比较左子树和右子树,记录最小值的Index
                    if (2 * i + 2 < dblArray.Length)
                    {
                        if (dblArray[2 * i + 1] > dblArray[2 * i + 2])
                            MinChildrenIndex = 2 * i + 2;
                    }
                    if (dblArray[i] > dblArray[MinChildrenIndex])
                    {
                        ExchageValue(ref dblArray[i], ref dblArray[MinChildrenIndex]);
                        NodeSort(ref dblArray, MinChildrenIndex);
                    }
                }
            }
        }

        /// 
        /// 节点排序
        /// 
        /// 
        /// 

        private static void NodeSort(ref double[] dblArray, int StartIndex)
        {
            while (2 * StartIndex + 1 < dblArray.Length)
            {
                int MinChildrenIndex = 2 * StartIndex + 1;
                if (2 * StartIndex + 2 < dblArray.Length)
                {
                    if (dblArray[2 * StartIndex + 1] > dblArray[2 * StartIndex + 2])
                    {
                        MinChildrenIndex = 2 * StartIndex + 2;
                    }
                }
                if (dblArray[StartIndex] > dblArray[MinChildrenIndex])
                {
                    ExchageValue(ref dblArray[StartIndex], ref dblArray[MinChildrenIndex]);
                    StartIndex = MinChildrenIndex;
                }
            }
        }

        /// 
        /// 交换值
        /// 
        /// 
        /// 

        private static void ExchageValue(ref double A, ref double B)
        {
            double Temp = A;
            A = B;
            B = Temp;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值