1 /*
2  * Copyright (c) 2025 Aerlync Labs Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <zephyr/sys/min_heap.h>
10 
11 struct data {
12 	int key;
13 	int value;
14 };
15 
compare(const void * a,const void * b)16 static int compare(const void *a, const void *b)
17 {
18 	const struct data *da = a;
19 	const struct data *db = b;
20 
21 	return da->key - db->key;
22 }
23 
match_key(const void * a,const void * b)24 static bool match_key(const void *a, const void *b)
25 {
26 	const struct data *da = a;
27 	const int *key = b;
28 
29 	return da->key == *key;
30 }
31 
32 #define HEAP_CAPACITY 8
33 
34 MIN_HEAP_DEFINE_STATIC(my_heap, HEAP_CAPACITY, sizeof(struct data),
35 		       __alignof__(struct data), compare);
36 
main(void)37 int main(void)
38 {
39 	void *elem;
40 	int target_key = 5;
41 	size_t index;
42 	struct data *top, *found, removed;
43 
44 	printk("Min-heap sample using static storage\n");
45 
46 	struct data elements[] = {
47 		{ .key = 10, .value = 100 },
48 		{ .key = 5,  .value = 200 },
49 		{ .key = 30, .value = 300 },
50 		{ .key = 2,  .value = 400 },
51 	};
52 
53 	for (int i = 0; i < ARRAY_SIZE(elements); i++) {
54 		if (min_heap_push(&my_heap, &elements[i]) != 0) {
55 			printk("Insert failed at index %d\n", i);
56 		}
57 	}
58 
59 	printk("Heap elements by order of priority:\n");
60 	MIN_HEAP_FOREACH(&my_heap, elem) {
61 		struct data *d = elem;
62 
63 		printk("key=%d value=%d\n", d->key, d->value);
64 	}
65 
66 	printk("Top of heap: ");
67 	top = min_heap_peek(&my_heap);
68 	if (top) {
69 		printk("key=%d value=%d\n", top->key, top->value);
70 	}
71 
72 	found = min_heap_find(&my_heap, match_key, &target_key, &index);
73 	if (found) {
74 		printk("Found element with key %d at index %zu,"
75 			 "removing it...\n", target_key, index);
76 		min_heap_remove(&my_heap, index, &removed);
77 	}
78 
79 	printk("Heap after removal:\n");
80 	MIN_HEAP_FOREACH(&my_heap, elem) {
81 		struct data *d = elem;
82 
83 		printk("key=%d value=%d\n", d->key, d->value);
84 	}
85 
86 	return 0;
87 }
88