Priority Queue reheapUp function not ordering correctly

I'm trying to write a function to maintain order in my priority queue however it doesn't seem to be working. The program compiles fine but i dont get the output in the correct order. I implemented the priority queue with a dynamically allocated array. I have a feeling its the way i passed in top in the enqueue function to the reheapUp. Any suggestions would be very helpful!

Function for enqueue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int PQueue::enqueue(int i)
{
    if(isFull())
    {
        std::cout << "No Space in Queue" << std::endl;
        return -1;
    }
    if(length <= capacity)
    {
        heap[length] = i;
        //
        //Reheapup
        //
        reheapUp(*heap, length);
        if(heap[length] == i)
        {
            length = length + 1;
            std::cout << "Successfull Enqueue" << std::endl;
            return 0;
        }
        else
        {
            std::cout << "Error in Enqueue" << std::endl;
            return -1;
        }
    }
    return -1;
}


reheapUp Function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void PQueue::reheapUp(int top, int bottom)
{
    int child = bottom;
    int parent;
    while(child > top)
    {
        parent = (child - 1)/2;
        if(heap[child] > heap[parent])
        {
            int newChild = parent;
            int newParent = child;
            heap[child] = newChild;
            heap[parent] = newParent;
        }
        child = parent;
    }
}
you seem to be quite confused about index and element.
reheapUp(*heap, length);
*heap is equivalent to `head[0]', that is, the first element.
So you pass the first element and the size of the queue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void PQueue::reheapUp(int top, int bottom) //the names suggest that they both refer to index
{
    int child = bottom; //child is clearly an index
    int parent;
    while(child > top) //so it should be comparing an index. However, ¿wouldn't top always be 0?
    {
        parent = (child - 1)/2;
        if(heap[child] > heap[parent])
        {
            int newChild = parent; //capturing the index...
            int newParent = child;
            heap[child] = newChild; //and then overwriting the element ¿?
            heap[parent] = newParent;
            //¿want to swap? use std::swap()
        }
        child = parent;
    }
}


also
1
2
3
        heap[length] = i;
        reheapUp(*heap, length);
        if(heap[length] == i) //¿if nothing was done? 

Last edited on
yeah! After looking over my notes again i was confusing the element and index. Thank you for clarifying the array part! As well as explaining it. It was more helpful than my notes!
Topic archived. No new replies allowed.