From 7f212106db5bbeec5d44ff28b4a4bcb16830d43c Mon Sep 17 00:00:00 2001 From: Bananymous Date: Thu, 7 Dec 2023 22:27:43 +0200 Subject: [PATCH] BAN: Implement heap sort --- BAN/include/BAN/Sort.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/BAN/include/BAN/Sort.h b/BAN/include/BAN/Sort.h index bf438a8a..294a6209 100644 --- a/BAN/include/BAN/Sort.h +++ b/BAN/include/BAN/Sort.h @@ -65,4 +65,39 @@ namespace BAN } } + template> + void sort_heap(It begin, It end, Comp comp = {}) + { + if (begin == end || next(begin, 1) == end) + return; + + It start = next(begin, distance(begin, end) / 2); + + while (prev(end, 1) != begin) + { + if (start != begin) + --start; + else + swap(*(--end), *begin); + + It root = start; + while (true) + { + size_t left_child = 2 * distance(begin, root) + 1; + if (left_child >= distance(begin, end)) + break; + + It child = next(begin, left_child); + if (next(child, 1) != end && comp(*child, *next(child, 1))) + ++child; + + if (!comp(*root, *child)) + break; + + swap(*root, *child); + root = child; + } + } + } + }