Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#53 from Triaro/patch-3
Browse files Browse the repository at this point in the history
heap_sort.m
  • Loading branch information
cozek authored Oct 4, 2020
2 parents 927d8e8 + 10ea1eb commit b8e44d6
Showing 1 changed file with 40 additions and 0 deletions.
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

0 comments on commit b8e44d6

Please sign in to comment.