Skip to content

Commit b8e44d6

Browse files
authored
Merge pull request #53 from Triaro/patch-3
heap_sort.m
2 parents 927d8e8 + 10ea1eb commit b8e44d6

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

algorithms/sorting/heap_sort.m

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
function list = heapSort(list)
2+
3+
function list = siftDown(list,root,theEnd)
4+
while (root * 2) <= theEnd
5+
6+
child = root * 2;
7+
if (child + 1 <= theEnd) && (list(child) < list(child+1))
8+
child = child + 1;
9+
end
10+
11+
if list(root) < list(child)
12+
list([root child]) = list([child root]); %Swap
13+
root = child;
14+
else
15+
return
16+
end
17+
18+
end %while
19+
end %siftDown
20+
21+
count = numel(list);
22+
23+
%Because heapify is called once in pseudo-code, it is inline here
24+
start = floor(count/2);
25+
26+
while start >= 1
27+
list = siftDown(list, start, count);
28+
start = start - 1;
29+
end
30+
%End Heapify
31+
32+
while count > 1
33+
34+
list([count 1]) = list([1 count]); %Swap
35+
count = count - 1;
36+
list = siftDown(list,1,count);
37+
38+
end
39+
40+
end

0 commit comments

Comments
 (0)