I am trying to sort three numbers without using inbuilt functions.What is wrong with the function?

7 views (last 30 days)
I am trying to sort three numbers without using inbuilt functions. The function takes a 3-element vector as its arguments and returns the 3 elements of the vector as 3 scalar output arguments in non-decreasing order.
function [small,medium,large] = sort_three(p)
if p(1)<=p(2)
if p(1)<=p(3)
small=p(1);
elseif p(1)>p(3)
medium=p(1);
small=p(3);
large=p(2);
return
end
elseif p(2)<=p(3)
if p(2)<=p(1)
small=p(2);
elseif p(2)>p(1)
small=p(1);
medium=p(2);
large=p(3);
return
end
else
small=p(3);
medium=p(2);
large=p(1);
return
end

Accepted Answer

James Tursa
James Tursa on 8 Dec 2016
Edited: James Tursa on 8 Dec 2016
Two of your branches do not set all three output variables. E.g.,
if p(1)<=p(2)
if p(1)<=p(3)
small=p(1); % <-- In this branch you never set medium and large
elseif p(1)>p(3)
:
And another branch later on has the same problem. So you need to fill in those branches. E.g.,
if p(1)<=p(2)
if p(1)<=p(3)
small=p(1); % <-- In this branch you never set medium and large
if( p(2) <= p(3)
medium = _____;
large = _____;
else
medium = _____;
large = _____;
end
else
:
You need to fill in the blanks above, and do the same for the other branch that needs code.
Also, you need to account for all of the possible cases in your last branch. So you will need to add another if-then-else construct there.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!