WEB开发网
开发学院软件开发C语言 C#实现所有经典排序算法汇总 阅读

C#实现所有经典排序算法汇总

 2009-05-06 08:27:04 来源:WEB开发网   
核心提示: 9、小根堆排序小根堆排序/// <summary> /// 小根堆排序 /// </summary> /// <param name="dblArray"></param> /// <param name="

9、小根堆排序

小根堆排序
 /// <summary>
        /// 小根堆排序
        /// </summary>
        /// <param name="dblArray"></param>
        /// <param name="StartIndex"></param>
        /// <returns></returns>

        private 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);
                    }
                }
            }
        }

        /// <summary>
        /// 节点排序
        /// </summary>
        /// <param name="dblArray"></param>
        /// <param name="StartIndex"></param>

        private 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;
                }
            }
        }

        /// <summary>
        /// 交换值
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        private void ExchageValue(ref double A, ref double B)
        {
            double Temp = A;
            A = B;
            B = Temp;
        }

注:部分算法来源于http://www.cnblogs.com/sun/

上一页  2 3 4 5 6 7 

Tags:实现 所有 经典

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接