# Thread: Priority Queue Array

1. ## Priority Queue Array

I have written a priority queue program using an array. It works except that the values pop out highest first. I could probably change the pop function to read from the end, but I would like to just fix whatever is wrong with the push function.

Here is the function:
Code:
```void PArrayClass:: pushData(int num)
{
if(rear<(MAX_SIZE-2))//make sure there is room to add something
{
for (int check=0; num<=data[check]; check++)
{
cout << check << ", " << data[check] << endl; //added to make sure this loop really did something
}//find where to insert new cell
for (int move=rear; move>=check; move--)
{
data[move+1]=data[move];
}//move all cells over one
data[check]=num;
rear++;
noOfItems++;
}
else
{
cout << "\nNo more room to add data.\n";
}
}```
The example I am using is the set {4, 5, 2}. I think the data should end up being stored in the array as {2, 4, 5} with 2 at index 0. This program is putting 5 at index 0.

If it makes any difference, I initialized the array to all 0's.

Thank you for your help.

2. I have written a priority queue program using an array. It works except that the values pop out highest first.
Isn't that the definition of a priority queue? This is how it should work.

3. Isn't that the definition of a priority queue? This is how it should work
Depends on what your priority is In his case the smaller number takes priority.

change this line:
Code:
`for (int check=0; num<=data[check]; check++)`
to this:
Code:
`for (int check=0; num>=data[check]; check++)`
and it should work.

4. Changing the

num<=data[check]

to

num>=data[check]

creates an infinite loop with the code the way it is since the array is initialized to zero. Maybe if I added a part to just put the first number into the array at index [0], then move on from there....that should work.

Thanks!!!

5. Oops, my bad. You would need to change it to this I believe - unfort I'm at work so can't test it.

if rear points to the first empty spot:
for (int check=0; num<=data[check] && check<rear; check++)

if rear points to last item in the array (what does it point to when array is empty? if it points to the zero spot, then you would need an extra check to see if queue is empty):
for (int check=0; num<=data[check] && check<=rear; check++)

6. Rear is set to -1 and front is 0 if there is no data in the array. Rear is incremented when an element is added (push), and front gets incremented when an element is used (pop).

I can't test anything right now either. At work too, otherwise the rotten thing would work by now.

Popular pages Recent additions