Sorting an array using Loops
14 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Image Analyst
on 6 Oct 2015
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 Comments
Joseph Cheng
on 6 Oct 2015
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!