Can someone tell me how to implement priority queues using arrays.Please help!!!!!!

Recommended Answers

All 3 Replies

There are a number of ways to do it depending on your efficiency needs. Usually a priority queue is optimized for maximum retrieval speed of the highest priority item. So you would do a sorted insert of new items according to the priority relation:

template <typename T>
void PQueue<T>::Insert(T item)
{
    if (Full())
    {
        throw FullQueueException();
    }

    if (Empty())
    {
        _data[_size++] = item;
    }
    else
    {
        for (int i = _size - 1; i >= 0; --i)
        {
            if (item <= _data[i])
            {
                break;
            }

            _data[i + 1] = _data[i];
        }

        _data[++_size] = item;
    }
}

Likewise you do a sorted removal of the highest priority item for deletion. This is actually quite trivial as the highest priority item should be either the first or last in the array (storing it as the last item makes removal very efficient while as the first item you need to do a potentially expensive shift). Doing the priority lookup is equally trivial as you just return the item at the 0th index or n-1th index depending on how you've chosen to do the sort.

Priority Queue is an abstact data type where each element in the queue ha its associated priority. Element eith higher priority will be processed first than the element with the lower priority.
Its 2 operations:
-inser_with_priority
-pull_hidgest_priority_element

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.