数据结构---堆的实现-C#

堆是一种数据结构,其实是一种用数组储存的数,并且满足一些特性:如果是最小化堆,那么儿子节点的值一定要比父亲节点大。

看代码:

 //最小化堆,根节点最小
    class Heap
    {
        private int[] m_heapArr;
        private int m_count;
        public Heap(int[] numbers,int arrSize)
        {
            m_heapArr = new List<int>(numbers).ToArray(); ;
            m_count = arrSize;

            makeHeap();
        }

        public int getRootValue()
        {
            return m_heapArr[0];
        }

        public void DeleteRoot()
        {
            Swap(0, m_count - 1);
            m_count--;
            shift_down(0);
        }

        private void makeHeap()
        {
            for (int i = getParentIdx(m_count-1); i >= 0; i--)
            {
                shift_down(i);
            }
        }

        private void shift_down(int pos)
        {
            if ( getSonLeftIdx(pos)==-1)
                return;

            bool done = false;
            while (!done)
            {
                int sonToExchange = getSonLeftIdx(pos) ;
                int sonRight = getSonRightIdx(pos);

                
                if (sonRight != -1)
                {

                    if (m_heapArr[sonToExchange] > m_heapArr[sonRight])
                    {
                        sonToExchange = sonRight;
                    }
                }

                if (m_heapArr[pos] > m_heapArr[sonToExchange])
                {
                    Swap(pos, sonToExchange);
                    pos = sonToExchange;
                }
                else
                {
                    done = true;
                }

                //已经没有儿子了
                if (getSonLeftIdx(pos)==-1)
                    return;
            }
        }

        private int getSonLeftIdx(int parent)
        {
            int son=2*parent+1;
            if(son>=m_count)
                return -1;
            return son;
        }

        private int getSonRightIdx(int parent)
        {
            int sonr=2*parent+2;
            if(sonr>=m_count)
                return -1;
            return sonr;
        }

        private int getParentIdx(int son)
        {
            if (son < 0)
                return -1;
            if (son == 0)
                return 0;

            return (son + 1) / 2 - 1;
            
        }


        private void Swap( int idx1, int idx2)
        {
            int temp = m_heapArr[idx1];
            m_heapArr[idx1] = m_heapArr[idx2];
            m_heapArr[idx2] = temp;
        }

        
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值