Skip to content

Instantly share code, notes, and snippets.

@quadrupleslap
Last active May 20, 2018 05:17
Show Gist options
  • Save quadrupleslap/f968031d4a868cf34eb8acd1881f88fd to your computer and use it in GitHub Desktop.
Save quadrupleslap/f968031d4a868cf34eb8acd1881f88fd to your computer and use it in GitHub Desktop.
A binary heap that hopefully works.
#include <assert.h>
#include <stdlib.h>
#define T int
typedef struct heap {
T* data;
size_t cap, len;
} Heap;
Heap heap_create(size_t cap) {
assert(cap > 0);
Heap heap = {
.data = malloc(cap * sizeof(T)),
.cap = cap,
.len = 0
};
return heap;
}
void heap_push(Heap* heap, T value) {
if (heap->len == heap->cap) {
heap->cap *= 2;
heap->data = realloc(heap->data, heap->cap * sizeof(T));
}
T* data = heap->data;
size_t i = heap->len++;
while (i > 0) {
size_t p = (i - 1) / 2;
if (value < data[p]) {
data[i] = data[p];
i = p;
} else {
break;
}
}
data[i] = value;
}
void heap_pop(Heap* heap) {
if (heap->len == 0) {
return;
}
T* data = heap->data;
T value = data[--heap->len];
size_t i = 0;
while (1) {
size_t c = 2*i + 2;
if (c < heap->len) {
if (data[c - 1] <= data[c]) {
c--;
}
} else if (c == heap->len) {
c--;
} else {
break;
}
if (value <= data[c]) {
break;
}
data[i] = data[c];
i = c;
}
data[i] = value;
}
T* heap_peek(Heap* heap) {
return heap->len != 0 ? heap->data : NULL;
}
void heap_destroy(Heap heap) {
free(heap.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment