Sorting an array using Loops
4 次查看(过去 30 天)
显示 更早的评论
Hi there, so i need to sort an array using loops and no intrinsic functions (teachers orders) I setup a loop function and managed to return the maximum, but upon trying to return the second highest, i get the wrong number. Any help is appreciated, I'm just looking for a nudge in the right direction.
time=[500 30 300 450 5000 15 100 100]; %years
%Function
max=inf;
for i=1:8(time);
if time(i)>=max
max1=time(i);
end
end
for i=1:8(time);
if time(i)>=max~=max1
max2=time(i);
end
end
clc
Here the display function displays max1 as 5000 correctly, but max2 is displayed as 100
Thanks!
0 个评论
回答(2 个)
Image Analyst
2015-10-6
max is a built-in function and you should not overwrite/destroy it by using a variable called max.
One hint: you never even set/update the badly-named max inside the loop.
Have you considered looking up sort routines pseudocode in wikipedia?
This sort of logical comparison is ambiguous at best and nonsense at worst: if time(i)>=max~=max1
0 个评论
Joseph Cheng
2015-10-6
Was there an issue with how Cedric edited your code because i do not see how the function is able to get max1 as 5000. specifically in the first for loop in no way is time(i) greater than infinity for max1 to be replaced by the current index of time.
After checking to make your for loops are formatted correctly i feel like it should just be "for i = 1:8" and not "for i= 1:8(time)" but like you say you just want a nudge and not full correction on your code. If you were able to get the max number selected, perhaps you could create a new temporary array with max removed/set to 0 and run the same loop again to find the next maximum number.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!