Search code examples
c#data-structuresqueuepriority-queue

PriorityQueue initialization in C# does not sort properly


I've attempted to implement this priority queue in c sharp. Here is my code:

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;
    }
}

However, in my end result, each item in the priortiyqueue is sorted correctly except for the first item I "get". The first one seems to be in a completely random order. Every other item seems to be in order. Not sure what I'm doing wrong here.


Solution

  • Simple minor error. In the Add function, 'parent' is initialized incorrectly. You should be subtracting one from 'child' not adding 1 to it. Should be this:

    int parent = (child - 1) / 2;