Microsoft内部PriorityQueue <t>中的错误?

时间:2017-05-27 20:44:09

标签: c# .net priority-queue

在PresentationCore.dll的.NET Framework中,有一个通用PriorityQueue<T>类,其代码可以找到here

我写了一个简短的程序来测试排序,结果并不是很好:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using MS.Internal;

namespace ConsoleTest {
    public static class ConsoleTest {
        public static void Main() {
            PriorityQueue<int> values = new PriorityQueue<int>(6, Comparer<int>.Default);
            Random random = new Random(88);
            for (int i = 0; i < 6; i++)
                values.Push(random.Next(0, 10000000));
            int lastValue = int.MinValue;
            int temp;
            while (values.Count != 0) {
                temp = values.Top;
                values.Pop();
                if (temp >= lastValue)
                    lastValue = temp;
                else
                    Console.WriteLine("found sorting error");
                Console.WriteLine(temp);
            }
            Console.ReadLine();
        }
    }
}

结果:

2789658
3411390
4618917
6996709
found sorting error
6381637
9367782

存在排序错误,如果样本量增加,排序错误的数量会按比例增加。

我做错了吗?如果没有,PriorityQueue类的代码中的错误位于哪里?

3 个答案:

答案 0 :(得分:77)

可以使用初始化向量[0, 1, 2, 4, 5, 3]重现行为。结果是:

  

[0,1,2,4,3,5]

(我们可以看到3被错误地放置)

Push算法是正确的。它以一种简单的方式构建一个小堆:

  • 从右下角开始
  • 如果该值大于父节点,则插入它并返回
  • 否则,请将父级置于右下角位置,然后尝试在父级位置插入值(并保持交换树直到找到正确的位置)

结果树是:

                 0
               /   \
              /     \
             1       2
           /  \     /
          4    5   3

问题在于Pop方法。它首先将顶部节点视为填充的“间隙”(因为我们弹出它):

                 *
               /   \
              /     \
             1       2
           /  \     /
          4    5   3

要填充它,它会搜索最低的直接孩子(在这种情况下:1)。然后它将值向上移动以填补空白(并且孩子现在是新的差距):

                 1
               /   \
              /     \
             *       2
           /  \     /
          4    5   3

然后它与新的差距完全相同,因此差距再次下降:

                 1
               /   \
              /     \
             4       2
           /  \     /
          *    5   3

当差距达到底部时,算法......采用树的最右边的值并用它来填补空白:

                 1
               /   \
              /     \
             4       2
           /  \     /
          3    5   *

既然差距位于最右下方的节点,它会递减_count以消除与树之间的差距:

                 1
               /   \
              /     \
             4       2
           /  \     
          3    5   

我们最终得到了......一堆破碎。

说实话,我不明白作者试图做什么,所以我无法修复现有的代码。最多,我可以将其与工作版本交换(从Wikipedia无耻地复制):

internal void Pop2()
{
    if (_count > 0)
    {
        _count--;
        _heap[0] = _heap[_count];

        Heapify(0);
    }
}

internal void Heapify(int i)
{
    int left = (2 * i) + 1;
    int right = left + 1;
    int smallest = i;

    if (left <= _count && _comparer.Compare(_heap[left], _heap[smallest]) < 0)
    {
        smallest = left;
    }

    if (right <= _count && _comparer.Compare(_heap[right], _heap[smallest]) < 0)
    {
        smallest = right;
    }

    if (smallest != i)
    {
        var pivot = _heap[i];
        _heap[i] = _heap[smallest];
        _heap[smallest] = pivot;

        Heapify(smallest);
    }
}

该代码的主要问题是递归实现,如果元素数量太大,将会中断。我强烈建议使用优化的第三方库。

编辑:我想我发现了什么缺失。在获取最右下角的节点后,作者忘记重新平衡堆:

internal void Pop()
{
    Debug.Assert(_count != 0);

    if (_count > 1)
    {
        // Loop invariants:
        //
        //  1.  parent is the index of a gap in the logical tree
        //  2.  leftChild is
        //      (a) the index of parent's left child if it has one, or
        //      (b) a value >= _count if parent is a leaf node
        //
        int parent = 0;
        int leftChild = HeapLeftChild(parent);

        while (leftChild < _count)
        {
            int rightChild = HeapRightFromLeft(leftChild);
            int bestChild =
                (rightChild < _count && _comparer.Compare(_heap[rightChild], _heap[leftChild]) < 0) ?
                    rightChild : leftChild;

            // Promote bestChild to fill the gap left by parent.
            _heap[parent] = _heap[bestChild];

            // Restore invariants, i.e., let parent point to the gap.
            parent = bestChild;
            leftChild = HeapLeftChild(parent);
        }

        // Fill the last gap by moving the last (i.e., bottom-rightmost) node.
        _heap[parent] = _heap[_count - 1];

        // FIX: Rebalance the heap
        int index = parent;
        var value = _heap[parent];

        while (index > 0)
        {
            int parentIndex = HeapParent(index);
            if (_comparer.Compare(value, _heap[parentIndex]) < 0)
            {
                // value is a better match than the parent node so exchange
                // places to preserve the "heap" property.
                var pivot = _heap[index];
                _heap[index] = _heap[parentIndex];
                _heap[parentIndex] = pivot;
                index = parentIndex;
            }
            else
            {
                // Heap is balanced
                break;
            }
        }
    }

    _count--;
}

答案 1 :(得分:17)

Kevin Gosse的回答确定了问题所在。虽然他对堆的重新平衡会起作用,但如果你修复了原始删除循环中的基本问题,则没有必要。

正如他所指出的那样,我们的想法是用最低,最右边的项目替换堆顶部的项目,然后将其筛选到正确的位置。它是对原始循环的简单修改:

internal void Pop()
{
    Debug.Assert(_count != 0);

    if (_count > 0)
    {
        --_count;
        // Logically, we're moving the last item (lowest, right-most)
        // to the root and then sifting it down.
        int ix = 0;
        while (ix < _count/2)
        {
            // find the smallest child
            int smallestChild = HeapLeftChild(ix);
            int rightChild = HeapRightFromLeft(smallestChild);
            if (rightChild < _count-1 && _comparer.Compare(_heap[rightChild], _heap[smallestChild]) < 0)
            {
                smallestChild = rightChild;
            }

            // If the item is less than or equal to the smallest child item,
            // then we're done.
            if (_comparer.Compare(_heap[_count], _heap[smallestChild]) <= 0)
            {
                break;
            }

            // Otherwise, move the child up
            _heap[ix] = _heap[smallestChild];

            // and adjust the index
            ix = smallestChild;
        }
        // Place the item where it belongs
        _heap[ix] = _heap[_count];
        // and clear the position it used to occupy
        _heap[_count] = default(T);
    }
}

另请注意,编写的代码存在内存泄漏。这段代码:

        // Fill the last gap by moving the last (i.e., bottom-rightmost) node.
        _heap[parent] = _heap[_count - 1];

不清除_heap[_count - 1]的值。如果堆正在存储引用类型,那么引用将保留在堆中,并且在堆的内存被垃圾收集之前无法进行垃圾回收。我不知道这个堆的使用位置,但是如果它很大并且存在很长时间,它可能会导致过多的内存消耗。答案是在复制后清除项目:

_heap[_count - 1] = default(T);

我的替换代码包含了该修复程序。

答案 2 :(得分:0)

在.NET Framework 4.8中不可复制

尝试使用以下PriorityQueue<T>测试在问题中链接到XUnit的.NET Framework 4.8实现中重现此问题,

public class PriorityQueueTests
{
    [Fact]
    public void PriorityQueueTest()
    {
        Random random = new Random();
        // Run 1 million tests:
        for (int i = 0; i < 1000000; i++)
        {
            // Initialize PriorityQueue with default size of 20 using default comparer.
            PriorityQueue<int> priorityQueue = new PriorityQueue<int>(20, Comparer<int>.Default);
            // Using 200 entries per priority queue ensures possible edge cases with duplicate entries...
            for (int j = 0; j < 200; j++)
            {
                // Populate queue with test data
                priorityQueue.Push(random.Next(0, 100));
            }
            int prev = -1;
            while (priorityQueue.Count > 0)
            {
                // Assert that previous element is less than or equal to current element...
                Assert.True(prev <= priorityQueue.Top);
                prev = priorityQueue.Top;
                // remove top element
                priorityQueue.Pop();
            }
        }
    }
}

...在所有一百万个测试用例中均成功:

enter image description here

因此,似乎Microsoft修复了其实现中的错误:

internal void Pop()
{
    Debug.Assert(_count != 0);
    if (!_isHeap)
    {
        Heapify();
    }

    if (_count > 0)
    {
        --_count;

        // discarding the root creates a gap at position 0.  We fill the
        // gap with the item x from the last position, after first sifting
        // the gap to a position where inserting x will maintain the
        // heap property.  This is done in two phases - SiftDown and SiftUp.
        //
        // The one-phase method found in many textbooks does 2 comparisons
        // per level, while this method does only 1.  The one-phase method
        // examines fewer levels than the two-phase method, but it does
        // more comparisons unless x ends up in the top 2/3 of the tree.
        // That accounts for only n^(2/3) items, and x is even more likely
        // to end up near the bottom since it came from the bottom in the
        // first place.  Overall, the two-phase method is noticeably better.

        T x = _heap[_count];        // lift item x out from the last position
        int index = SiftDown(0);    // sift the gap at the root down to the bottom
        SiftUp(index, ref x, 0);    // sift the gap up, and insert x in its rightful position
        _heap[_count] = default(T); // don't leak x
    }
}

由于问题中的链接仅指向Microsoft源代码的最新版本(当前为.NET Framework 4.8),因此很难说出代码中到底发生了什么更改,但是最值得注意的是,现在有明确的注释不是< / strong>泄漏内存,因此我们可以假定@JimMischel的答案中提到的内存泄漏也已解决,可以使用Visual Studio诊断工具来确认:

enter image description here

如果发生内存泄漏,我们将在进行几百万次Pop()操作后在此处看到一些变化...