2 * Copyright (C) 2024 Mikulas Patocka
4 * This file is part of Ajla.
6 * Ajla is free software: you can redistribute it and/or modify it under the
7 * terms of the GNU General Public License as published by the Free Software
8 * Foundation, either version 3 of the License, or (at your option) any later
11 * Ajla is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along with
16 * Ajla. If not, see <https://www.gnu.org/licenses/>.
21 type heap(key : type, cls : class_ord(key));
23 fn heap_init(key : type, const cls : class_ord(key)) : heap(key, cls);
24 fn heap_size(key : type, const cls : class_ord(key), h : heap(key, cls)) : int;
25 fn heap_is_nonempty(key : type, const cls : class_ord(key), h : heap(key, cls)) : bool;
26 fn heap_peek(key : type, const cls : class_ord(key), h : heap(key, cls)) : key;
27 fn heap_extract(key : type, const cls : class_ord(key), h : heap(key, cls)) : (heap(key, cls), key);
28 fn heap_insert(key : type, const cls : class_ord(key), h : heap(key, cls), k : key) : heap(key, cls);
29 fn heap_from_list(key : type, const cls : class_ord(key), l : list(key)) : heap(key, cls);
33 type heap(key : type, cls : class_ord(key)) := list(key);
35 fn heap_init(key : type, const cls : class_ord(key)) : heap(key, cls)
40 fn heap_size(key : type, const cls : class_ord(key), h : heap(key, cls)) : int
45 fn heap_is_nonempty(key : type, const cls : class_ord(key), h : heap(key, cls)) : bool
47 return len_greater_than(h, 0);
50 fn heap_peek(key : type, const cls : class_ord(key), h : heap(key, cls)) : key
55 fn heap_left~inline(i : int) : int := i + i + 1;
56 fn heap_right~inline(i : int) : int := i + i + 2;
57 fn heap_parent~inline(i : int) : int := (i - 1) shr 1;
59 fn heap_extract(key : type, const implicit cls : class_ord(key), h : heap(key, cls)) : (heap(key, cls), key)
62 var ins := h[len(h) - 1];
63 h := h[ .. len(h) - 1];
69 var left := heap_left(idx);
70 var right := heap_right(idx);
71 if left >= len(h) then
73 if h[left] >= h[idx] then [
74 if right >= len(h) then
76 if h[right] >= h[idx] then
79 h[idx], h[right] := h[right], h[idx];
83 if right < len(h), h[right] <= h[left] then
85 h[idx], h[left] := h[left], h[idx];
93 fn heap_insert(key : type, const implicit cls : class_ord(key), h : heap(key, cls), k : key) : heap(key, cls)
96 var idx := len(h) - 1;
98 var parent := heap_parent(idx);
99 if h[parent] < h[idx] then
101 h[idx], h[parent] := h[parent], h[idx];
107 fn heap_from_list(key : type, const implicit cls : class_ord(key), l : list(key)) : heap(key, cls)
109 var h := heap_init(key, cls);
111 h := heap_insert(h, f);