标签:Heap

[C#]Make Heap

[C#]Make Heap

写的略蠢……把一个数组转成堆的形式

    public class Heap
    {
        public HeapNode Root = new HeapNode();
        public void Heapify(HeapNode CurrNode)
        {
            int Select = 0;//0:Curr 1:Right 2:Left
            if ((CurrNode.L != null && CurrNode.Value > CurrNode.L.Value) && ((CurrNode.R != null && CurrNode.Value > CurrNode.R.Value) || (CurrNode.R == null))) Select = 0;
            else if (CurrNode.L != null && CurrNode.Value > CurrNode.L.Value) Select = 1;
            else if (CurrNode.R != null) Select = 2;
            if (Select == 1)
            {
                int temp = CurrNode.Value;
                CurrNode.Value = CurrNode.R.Value;
                CurrNode.R.Value = temp;
                Heapify(CurrNode.R);
            }
            if (Select == 2)
            {
                int temp = CurrNode.Value;
                CurrNode.Value = CurrNode.L.Value;
                CurrNode.L.Value = temp;
                Heapify(CurrNode.L);
            }
        }
        public void MakeHeap(HeapNode CurrNode)
        {
            if (CurrNode.L != null) MakeHeap(CurrNode.L);
            if (CurrNode.R != null) MakeHeap(CurrNode.R);
            Heapify(CurrNode);
        }
        public HeapNode IntData(int[] a, int CurrPos)
        {
            HeapNode Node = new HeapNode();
            if (a.Length < CurrPos + 1) return null;
            Node.Value = a[CurrPos];
            Node.L = IntData(a, (CurrPos + 1) * 2 - 1);
            Node.R = IntData(a, (CurrPos + 1) * 2);
            return Node;
        }
        public Heap(int[] a)
        {
            Root = IntData(a, 0);
            MakeHeap(Root);
        }
    }