【问题标题】:PriorityQueue initialization in C# does not sort properlyC# 中的 PriorityQueue 初始化未正确排序
【发布时间】:2018-07-11 22:13:23
【问题描述】:

我尝试在 c sharp 中实现这个优先级队列。 这是我的代码:

public class PriorityQueue<T> where T : IComparable<T>
{
    private List<T> data;

    public PriorityQueue()
    {
        this.data = new List<T>();
    }

    public void Add(T item)
    {
        data.Add(item);
        int child = data.Count - 1;
        while (child > 0)
        {
            int parent = (child + 1) / 2;
            if ((data[child].CompareTo(data[parent])) >= 0)
                break;

            T temp = data[child];
            data[child] = data[parent];
            data[parent] = temp;
            child = parent;
        }
    }

    public T Get()
    {
        int last = data.Count - 1;
        T root = data[0];
        data[0] = data[last];
        data.RemoveAt(last);
        --last;

        int parent = 0;
        while (true)
        {
            int child = (parent * 2) + 1;
            if (child > last)
                break;
            if (child > last)
                break;
            int next = child + 1;
            if (next <= last && data[next].CompareTo(data[child]) < 0)
                child = next;

            if (data[parent].CompareTo(data[child]) <= 0)
                break;

            T temp = data[parent];
            data[parent] = data[child];
            data[child] = temp;
            parent = child;
        }
        return root;
    }

    public int Count()
    {
        return data.Count;
    }
}

但是,在我的最终结果中,priortiyqueue 中的每个项目都被正确排序,除了我“得到”的第一个项目。第一个似乎是完全随机的顺序。其他所有项目似乎都井井有条。不知道我在这里做错了什么。

【问题讨论】:

    标签: c# data-structures queue priority-queue


    【解决方案1】:

    简单的小错误。在 Add 函数中,'parent' 被错误地初始化。你应该从 'child' 中减去一个而不是加 1。应该是这样的:

    int parent = (child - 1) / 2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2012-06-17
      • 2022-01-22
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多