【c#】堆排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/suzan_bingtong/article/details/82085875

堆排序

堆排序的解释网上有好多,都比我解释的清楚多了,再次不在过多解释。

代码

代码亲测正确

namespace 堆排序
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int[] lst = new int[6] { 4, 9, 5, 1, 7, 3 };

                foreach (var item in lst)
                {
                    Console.WriteLine(item + ", ");
                }
                Console.WriteLine("---------------------------");

                int maxid = GetMax(lst.Length, lst);
                HeapSort(maxid, lst);

                foreach (var item in lst)
                {
                    Console.WriteLine(item + ", ");
                }

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 交换
        /// </summary>
        /// <param name="maxIdx">无序区最大值Idx</param>
        /// <param name="idx">有序区目标位置</param>
        /// <param name="lst">序列</param>
        public static void Swap(int maxIdx, int idx, int[] lst)
        {
            int midx = maxIdx;
            int temp = lst[idx];
            lst[idx] = lst[maxIdx];
            lst[maxIdx] = temp;
        }

        /// <summary>
        /// 获取无序区最大值
        /// </summary>
        /// <param name="maxLen">无序区最大长度</param>
        /// <param name="lst">序列</param> 
        public static int GetMax(int maxLen, int[] lst)
        {
            int maxIdx = 0;
            for (var i = 0; i < maxLen; i++)
            {
                if (lst[i] > lst[maxIdx])
                    maxIdx = i;
            }

            return maxIdx;
        }

        /// <summary>
        /// 堆排序
        /// </summary>
        /// <param name="maxIdx">无序区最大值位置</param>
        /// <param name="lst">序列</param>
        /// <returns>序列</returns>
        public static IList<int> HeapSort(int maxIdx, int[] lst)
        {
            int i = lst.Length - 1;
            int k = 0;

            while (i > -1)
            {
                Swap(maxIdx, i, lst);
                k++;
                //每次缩短无序区最大位置
                maxIdx = GetMax(lst.Length - k, lst);
                i--;
            }

            return lst;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/suzan_bingtong/article/details/82085875
今日推荐