From 10ea1ebfac23be2ca23047dc2970a20fca1c5eeb Mon Sep 17 00:00:00 2001 From: Abhishek Mehra <52788025+Triaro@users.noreply.github.com> Date: Fri, 2 Oct 2020 10:55:36 +0530 Subject: [PATCH] heap_sort.m sorting algorithm --- algorithms/sorting/heap_sort.m | 40 ++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 algorithms/sorting/heap_sort.m diff --git a/algorithms/sorting/heap_sort.m b/algorithms/sorting/heap_sort.m new file mode 100644 index 0000000..df52e1e --- /dev/null +++ b/algorithms/sorting/heap_sort.m @@ -0,0 +1,40 @@ +function list = heapSort(list) + + function list = siftDown(list,root,theEnd) + while (root * 2) <= theEnd + + child = root * 2; + if (child + 1 <= theEnd) && (list(child) < list(child+1)) + child = child + 1; + end + + if list(root) < list(child) + list([root child]) = list([child root]); %Swap + root = child; + else + return + end + + end %while + end %siftDown + + count = numel(list); + + %Because heapify is called once in pseudo-code, it is inline here + start = floor(count/2); + + while start >= 1 + list = siftDown(list, start, count); + start = start - 1; + end + %End Heapify + + while count > 1 + + list([count 1]) = list([1 count]); %Swap + count = count - 1; + list = siftDown(list,1,count); + + end + +end