Search code examples
c++queuepriority-queuetraversal

Implementing Priority Queue


I am attempting to implement insertion, find minimum, and delete minimum functions for a primary queue. I also have tests to ensure that my code is working properly by checking it alongside another queue. For some reason, when utilizing the find minimum and delete minimum functions, it is coming with different values from the other queue. How can I fix this?

#include "pQueue.h"
#include <iostream>
using namespace tom;

status pQueue::insert(int insertInt)
{

    if (q[0] == NULL)
    {
        q[0] = insertInt;
        minimum = insertInt;
    }
    else if (q[0] != NULL)
    {
        q[count] = insertInt;
    }
    else
    {
        return FAILURE;
    }

    if (insertInt < minimum)
    {
        minimum = insertInt;
    }
    return SUCCESS;
    count++;

}

status pQueue::findMin(int &minElement)
{

    minElement = minimum;

    if (minElement == NULL)
    {
        return FAILURE;
    }
    return SUCCESS;
}

status pQueue::deleteMin()
{

    for (int i = 0; i <= count; i++)
    {
        if (q[i] = minimum)
        {
            q[i] = 0;
        }
        if (q[i] != 0)
        {
            return FAILURE;
        }

    }
}

Solution

  • The general idea for an unsorted priority queue is, assuming you're storing it in an array, is:

    Insertion:

    1. Add item as the last item in the array.
    2. Increment count.

    Removal:

    1. Scan the array to find the index of the smallest item.
    2. Copy the value from that index to a variable called result
    3. Copy the last value in the array to that location
    4. Decrement count.
    5. Return result

    So insert becomes (in pseudo-code)

    insert(value)
        a[count] = value
        count = count + 1
    

    deleteMin is:

    deleteMin()
        minIndex = findMinIndex()
        result = a[minIndex]
        a[minIndex] = a[count-1]
        count = count - 1
        return result
    

    findMinIndex is:

    findMinIndex()
        if (count < 1) then error
        minIndex = 0
        for (i = 1; i < count; ++i)
            if (a[i] < a[minIndex])
                minIndex = i
        return minIndex
    

    And findMin is:

    findMinIndex()
        return a[findMinIndex()]
    

    I'll leave the C++ implementation to you.