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

21 views (last 30 days)
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 Comments
Jessica Avellaneda
Jessica Avellaneda on 7 Nov 2020
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 on 7 Nov 2020
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:

Sign in to comment.

Answers (3)

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

Star Strider
Star Strider on 17 Oct 2014
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 Comments

Sign in to comment.


Sean de Wolski
Sean de Wolski on 17 Oct 2014
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

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!