示例#1
0
        /// <summary>
        /// 添加值
        /// </summary>
        /// <param name="value"></param>
        public void Add(T value)
        {
            var newNode = new HeapNode <T>(value);

            Count++;
            newNode.index = Count - 1;
            _container.Add(newNode);
            // _container[newNode.index] = newNode;

            if (_root == null)
            {
                _root = newNode;
            }
            else
            {
                var parent = _container[(int)Math.Ceiling(System.Convert.ToDouble(Count) / 2) - 1];
                newNode.parent = parent;
                if (Count % 2 == 0)
                {
                    //偶数,则添加到左节点
                    parent.left = newNode;
                }
                else
                {
                    //奇数,则添加到右节点
                    parent.right = newNode;
                }
                CompareToParent(newNode);
            }
        }
示例#2
0
        private void CompareToChildren(HeapNode <T> parent)
        {
            if (parent.left == null)
            {
                return;
            }

            HeapNode <T> toSwitchNode = parent.left;

            if (parent.right != null)
            {
                var compareResultForChildren = parent.left.value.CompareTo(parent.right.value);
                if (compareResultForChildren == -1)
                {
                    toSwitchNode = parent.right;
                }
            }
            var compareResult = parent.value.CompareTo(toSwitchNode.value);

            if (compareResult == 1)
            {
                return;
            }

            SwitchValue(parent, toSwitchNode);
            CompareToChildren(toSwitchNode);
        }
示例#3
0
        private void CompareToParent(HeapNode <T> child)
        {
            if (child == _root)
            {
                return;
            }
            var compareResult = child.value.CompareTo(child.parent.value);

            if (compareResult == 1)
            {
                SwitchValue(child, child.parent);
                CompareToParent(child.parent);
            }
        }
示例#4
0
 public MybinaryHeap()
 {
     _root      = null;
     Count      = 0;
     _container = new List <HeapNode <T> >();
 }