Inputs a Vector and Returns the Second Smallest Element
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
James Tursa
2020-9-17
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!