insert
Lesson 5 of 14 in Coddy's Heaps & Priority Queues - Data Structures Series #7 course.
Challenge
EasyAdd a method insert to the MinHeap class.
It gets an integer value:
- Append
valueat the end ofheap. - siftUp: while the new element is smaller than its parent, swap them. Stop when it is no longer smaller, or when you reach the root.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "minheap.h"
int main() {
MinHeap h;
MinHeap_init(&h);
char line[1024];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "insert") == 0) { char* arg = strtok(NULL, " \t"); if (arg) MinHeap_insert(&h, atoi(arg)); }
if (strcmp(cmd, "dump") == 0) {
for (int idx = 0; idx < h.count; idx++) { if (idx > 0) printf(" "); printf("%d", h.heap[idx]); }
printf("\n");
}
}
return 0;
}