/* * Copyright (c) Camden Dixie O'Brien * SPDX-License-Identifier: AGPL-3.0-only */ #include "min_heap.h" static inline int left(int i) { return 2 * i + 1; } static inline int parent(int i) { return (i - 1) / 2; } static inline void swap(int *xs, int a, int b) { int tmp = xs[a]; xs[a] = xs[b]; xs[b] = tmp; } static void sift_down(int *xs, int root, int count) { int child; while ((child = left(root)) < count) { if (child + 1 < count && xs[child] > xs[child + 1]) ++child; if (xs[root] > xs[child]) { swap(xs, root, child); root = child; } else { return; } } } void min_heap_heapify(int *xs, int count) { for (int i = parent(count - 1); i >= 0; --i) sift_down(xs, i, count); } int min_heap_pop(int *xs, int *count) { int min = xs[0]; --(*count); xs[0] = xs[*count]; sift_down(xs, 0, *count); return min; }