Sorting algorithms/Heapsort: Difference between revisions

Added a solution for MATLAB
(Added a solution for MATLAB)
Line 811:
heapsort(`a')
show(`a')</lang>
 
=={{header|MATLAB}}==
This function definition is an almost exact translation of the pseudo-code into MATLAB, but I have chosen to make the heapify function inline because it is only called once in the pseudo-code.
 
<lang MATLAB>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</lang>
 
Sample Usage:
<lang MATLAB>>> heapSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</lang>
 
 
=={{header|OCaml}}==
Anonymous user