Implement min heap
This commit is contained in:
@@ -2,6 +2,7 @@ add_library(lib
|
||||
construct.c
|
||||
desugar.c
|
||||
fsa.c
|
||||
min_heap.c
|
||||
parse.c
|
||||
regex.c
|
||||
)
|
||||
|
||||
12
lib/include/min_heap.h
Normal file
12
lib/include/min_heap.h
Normal file
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright (c) Camden Dixie O'Brien
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
#ifndef MIN_HEAP_H
|
||||
#define MIN_HEAP_H
|
||||
|
||||
void min_heap_heapify(int *xs, int count);
|
||||
int min_heap_pop(int *xs, int *count);
|
||||
|
||||
#endif
|
||||
53
lib/min_heap.c
Normal file
53
lib/min_heap.c
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
Reference in New Issue
Block a user