Exemplo n.º 1
0
        private void SwapValue(BinaryHeapNode <T> a, BinaryHeapNode <T> b)
        {
            T temp = a.Value;

            a.Value = b.Value;
            b.Value = temp;
        }
Exemplo n.º 2
0
        private void Sink(BinaryHeapNode <T> node)
        {
            if (node.LeftChild == null)
            {
                return;
            }

            if (node.RightChild == null)
            {
                if (node.Value.CompareTo(node.LeftChild.Value) > 0)
                {
                    SwapValue(node, node.LeftChild);
                    Sink(node.LeftChild);
                }
            }
            else
            {
                BinaryHeapNode <T> compareNode = node.LeftChild.Value.CompareTo(node.RightChild.Value) < 0 ? node.LeftChild : node.RightChild;
                if (node.Value.CompareTo(compareNode.Value) > 0)
                {
                    SwapValue(node, compareNode);
                    Sink(compareNode);
                }
            }
        }
Exemplo n.º 3
0
        public BinaryHeap()
        {
            NodeList = new List <BinaryHeapNode <T> >();
            //填充一个空位作为根节点的父节点(value=null),目的是后面在添加新节点时方便为新节点寻找父节点
            //父节点index = 子节点index >> 1
            BinaryHeapNode <T> baseNode = new BinaryHeapNode <T>()
            {
                Index = 0
            };

            Root            = baseNode;
            Last            = baseNode;
            baseNode.Parent = baseNode;
            NodeList.Add(baseNode);
        }
Exemplo n.º 4
0
        private void FloatLast()
        {
            BinaryHeapNode <T> temp = Last;

            while (temp.Parent.Value != null)
            {
                if (temp.Value.CompareTo(temp.Parent.Value) < 0)
                {
                    SwapValue(temp, temp.Parent);
                    temp = temp.Parent;
                }
                else
                {
                    break;
                }
            }
        }
Exemplo n.º 5
0
        private void AddNewChild()
        {
            BinaryHeapNode <T> newNode = new BinaryHeapNode <T>();

            newNode.Index = NodeList.Count;
            NodeList.Add(newNode);
            Last           = newNode;
            newNode.Parent = NodeList[newNode.Index >> 1];

            if (newNode.Parent.Value != null)
            {
                newNode.Parent.SetChild(newNode);
            }
            else
            {
                Root = newNode;
            }
        }
Exemplo n.º 6
0
 public void SetChild(BinaryHeapNode <T> childNode)
 {
     Childs[(childNode.Index & 1)] = childNode;
 }