How can I return a vector sorting from least to greatest without using the "sort" command?

6 次查看(过去 30 天)
If you a given a vector v=[4 2 7 4 12 9] how can I return this vector sorted from least to greatest without using the "sort" command. Is there a way of achieving this using loops?
  5 个评论
Jessica Avellaneda
Jessica Avellaneda 2020-11-7
Hi! I would like to know how could you that if I want the vector sorting from GREATEST to LEAST without using the "sort", "min", "max" commands.
Thank you!
Image Analyst
Image Analyst 2020-11-7
Jessica, then you'd have to manually write your own version of sort, min and max. No one here wants to do that since there are already built in functions for that. The only people who say they need to do things manually without using the full power of built-in MATLAB functions are students doing homework assignments. And in that situation of course, we cannot provide the code (even if we did want to write it) because students are not allowed to turn in someone elses work as their own. I'm sure you can find pseudocode for sorting on Wikipedia or elsewhere. So good luck. If you still need help, see the following links:

请先登录,再进行评论。

回答(3 个)

Image Analyst
Image Analyst 2014-10-17
Algorithms you can follow are given here: http://en.wikipedia.org/wiki/Sorting_algorithm

Star Strider
Star Strider 2014-10-17
Probably the easiest way:
v=[4 2 7 4 12 9];
for k1 = 1:length(v)
[sv(k1),ix] = min(v); % Find Minimum & Index
v(ix) = []; % Set Previous Minimum To Empty
end
v = sv % Output
  4 个评论

请先登录,再进行评论。


Sean de Wolski
Sean de Wolski 2014-10-17
One of the guys we play cards with sorts this way. Makes for long games but works for a small number of cards
v = [4 2 7 4 12 9];
while 1
idx = randperm(numel(v));
if issorted(v(idx))
vsort = v(idx);
break
end
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by