堆排序(HeapSort)

堆排序(HeapSort)

动图显示:
这里写图片描述

  1. 将数组当作二叉树来进行处理
  2. 将二叉树构造成大顶堆(根节点的值大于或等于左右子树的值)或小顶堆(根节点的值小于或等于左右子树的值)
  3. 将二叉树的头结点和树的最末端交换(此时数组末尾是最大值),然后对剩下的length-1个数再进行构造大顶堆操作再将树的头结点和树的末端交换。。。(依次进行下去)
    这里写图片描述
using System;

namespace cchoop
{
    class Program
    {
        public static void Main()
        {
            int[] arr = { 50, 10, 90, 30, 70, 40, 80, 60, 100 };
            HeapSort(arr);

            foreach (var item in arr)
            {
                Console.Write(item + " ");
            }
        }

        //堆排序
        public static void HeapSort(int[] arr)
        {
            int length = arr.Length;

            for (int i = 0; i < length; i++)
            {
                BuildMaxHead(arr, (length - i) / 2 - 1, length - i);
                int maxValue = arr[0];
                arr[0] = arr[length - i - 1];
                arr[length - i - 1] = maxValue;
            }
        }

        //构造大顶堆
        public static void BuildMaxHead(int[] arr, int endIndex, int treeEndingIndex)
        {
            for (int i = endIndex; i >= 0; i--)
            {
                int maxIndex = i;
                if (arr[2 * i + 1] > arr[maxIndex])
                {
                    maxIndex = 2 * i + 1;
                }
                if ((2 * i + 2) < treeEndingIndex && arr[2 * i + 2] > arr[maxIndex])
                {
                    maxIndex = 2 * i + 2;
                }
                if (maxIndex != i)
                {
                    int temp = arr[i];
                    arr[i] = arr[maxIndex];
                    arr[maxIndex] = temp;
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cchoop

有用的话请杯肥宅水

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值