Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions algorithms/sorting/heap_sort.m
Original file line number Diff line number Diff line change
@@ -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