Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- int priority;
- int value;
- } Item;
- typedef struct {
- Item* heap;
- int capacity;
- int size;
- } HeapQueue;
- HeapQueue* hq_create(int capacity) {
- HeapQueue* hq = (HeapQueue*)malloc(sizeof(HeapQueue));
- hq->capacity = capacity;
- hq->size = 0;
- hq->heap = (Item*)malloc(capacity * sizeof(Item));
- return hq;
- }
- void hq_destroy(HeapQueue* hq) {
- free(hq->heap);
- free(hq);
- }
- void hq_enqueue(HeapQueue* hq, int priority, int value) {
- if (hq->size == hq->capacity) {
- fprintf(stderr, "HeapQueue is full. Cannot enqueue.\n");
- return;
- }
- Item item = { priority, value };
- int i = hq->size++;
- int parent = (i - 1) / 2;
- while (i > 0 && hq->heap[parent].priority > item.priority) {
- hq->heap[i] = hq->heap[parent];
- i = parent;
- parent = (i - 1) / 2;
- }
- hq->heap[i] = item;
- }
- Item hq_dequeue(HeapQueue* hq) {
- if (hq->size == 0) {
- fprintf(stderr, "HeapQueue is empty. Cannot dequeue.\n");
- return (Item){0, 0};
- }
- Item root = hq->heap[0];
- Item last = hq->heap[--hq->size];
- int i = 0;
- int child = 1;
- while (child < hq->size) {
- if (child + 1 < hq->size && hq->heap[child + 1].priority < hq->heap[child].priority) {
- child++;
- }
- if (last.priority <= hq->heap[child].priority) {
- break;
- }
- hq->heap[i] = hq->heap[child];
- i = child;
- child = 2 * i + 1;
- }
- hq->heap[i] = last;
- return root;
- }
- int main() {
- HeapQueue* hq = hq_create(10);
- hq_enqueue(hq, 2, 20);
- hq_enqueue(hq, 4, 40);
- hq_enqueue(hq, 1, 10);
- hq_enqueue(hq, 3, 30);
- while (hq->size > 0) {
- Item item = hq_dequeue(hq);
- printf("Priority: %d, Value: %d\n", item.priority, item.value);
- }
- hq_destroy(hq);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement