0

I have this code which pops the highest priority node from the queue. Currently the highest priority is defined as 1. I would like to change this so the highest priority is from 10 -> 1. To clarify the problem is in the pop function, others are added simply for context.

Node and heap definitions:

struct intnode {
    int value;
    int priority;
};
typedef struct intnode IntNode;

struct heap {
    IntNode *nodes;
    int len;
    int size;
};
typedef struct heap heap_t;

Here is the push function of the queue:

void push (heap_t *h, int priority, int value) {
    if (h->len + 1 >= h->size) {
        if(h->size) {
            h->size = h->size * 2;
        } 
        else {
            h->size = 4;
        }

        h->nodes = (IntNode *)realloc(h->nodes, h->size * sizeof (IntNode));
    }

    int i = h->len + 1;
    int j = i / 2;

    while (i > 1 && h->nodes[j].priority > priority) {
        h->nodes[i] = h->nodes[j];
        i = j;
        j = j / 2;
    }

    h->nodes[i].value = value;
    h->nodes[i].priority = priority;
    h->len++;
}

The pop function of the queue:

int pop (heap_t *h) {
    int i, j, k;

    if (!h->len) {
        return -1;
    }

    int value = h->nodes[1].value;

    h->nodes[1] = h->nodes[h->len];
    h->len--;
    i = 1;

    while (1) {
        k = i;
        j = 2 * i;

        if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
            k = j;
        }
        if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
            k = j + 1;
        }
        if (k == i) {
            break;
        }

        h->nodes[i] = h->nodes[k];
        i = k;
    }

    h->nodes[i] = h->nodes[h->len + 1];

    return value;
}

Thank you for your time!

Josh G
  • 1
  • 1

1 Answers1

0

Just push your Elements with 11 - your priority

Tomas Dittmann
  • 424
  • 7
  • 18