Inputs a Vector and Returns the Second Smallest Element

4 views (last 30 days)
I am writing a script that takes as input a nonempty vector v and returns the second smallest element. I have a block of code written that runs, however it does not compute the correct answer. I am not sure why the program does not run correctly.
Here is what I have:
function SecondSmallest = ex1(v)
%
%
vLength = length(v);
Smallest = v(1);
CurrentPosition = 2;
while CurrentPosition <= vLength
if v(CurrentPosition) <= Smallest
Smallest = v(CurrentPosition);
SecondSmallest = v(1);
else
Smallest = v(1);
SecondSmallest = v(CurrentPosition);
end
CurrentPosition = CurrentPosition + 1;
end

Answers (1)

James Tursa
James Tursa on 17 Sep 2020
Your algorithm always replaces Smallest and SecondSmallest at each iteration. Does that make sense? E.g., if the current Smallest = 5 and SecondSmallest = 7, and v(CurrentPosition) = 10, should your algorithm be replacing either of them? No, it shouldn't. But your algorithm does. You need to step through this one line at a time with a small example vector to see what is going wrong and change your logic. In some iterations your algorithm should not be replacing either of Smallest or SecondSmallest. So the if-test inside your loop should have logic for doing nothing. E.g.,
if( v(CurrentPosition) < Smallest )
% do something
elseif( v(CurrentPosition) < SecondSmallest )
% do something
end
With the above logic, if neither of the tests is satisfied, then nothing is done to Smallest or SecondSmallest.

Tags

Community Treasure Hunt

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

Start Hunting!