11 #include "graph-private.h" 31 static void swap(
Node **arr,
int i,
int j)
47 static void bubble_up(
Node **arr,
size_t pos)
50 size_t parent_pos = (pos - 1) / 2;
51 while (parent_pos != pos && arr[parent_pos]->dist > arr[pos]->dist) {
52 swap(arr, parent_pos, pos);
56 parent_pos = (pos - 1) / 2;
68 static void bubble_down(
Node **arr,
size_t maxidx,
size_t root)
71 while ((child = 2 * root + 1) < maxidx) {
74 if (arr[root]->dist > arr[child]->dist) {
77 if (child + 1 < maxidx && arr[swp]->dist > arr[child + 1]->dist) {
92 Heap *h = malloc(
sizeof *h);
96 h->data = graph_dup_data(g, &h->size);
101 for (
size_t i = 0; i < h->size; i++) {
103 h->data[i]->dist = UINT_MAX;
104 h->data[i]->previous = NULL;
111 return h ? h->size == 0 :
true;
118 swap(h->data, 0, h->size);
119 bubble_down(h->data, h->size, 0);
120 return h->data[h->size];
125 if (!h || !n)
return;
126 assert(val < n->dist);
129 bubble_up(h->data, n->idx);
bool heap_is_empty(Heap *h)
Test if a heap is empty.
Heap * heap_new_from_graph(Graph *g)
Create new heap with nodes from given graph.
void heap_free(Heap *h)
Free all memory used by the heap.
struct node Node
Node is an opaque type.
Interface for creating and working with heap.
void heap_decrease_distance(Heap *h, Node *n, unsigned int val, Node *prev)
Decrease distance of a certain node.
struct heap Heap
Heap is an opaque structure.
Node * heap_extract_min(Heap *h)
Remove minimal element from the heap, i.e.
struct graph Graph
Graph is an opaque type.