using a for loop to sort a vector without sort or max/min functions

47 views (last 30 days)
I am trying to use a for loop to sort a vector. I do not want to use sort,max,min function.
this is what i have so far, i cant figure out why its not outputing the right order, please help
function [sorted] = mySort(vec)
vec = [4 5 2 3];
l = length(vec)-1;
for i=2:l
if vec(1)<vec(i)
vec(1) = vec(1);
end
if vec(i)<vec(i+1)
vec(i)=vec(i);
else
vec(i)=vec(i+1);
end
end
sorted = vec;
end

Answers (1)

MisterQuax
MisterQuax on 21 Oct 2022
Hello,
so first, instead of swapping places in the else part, you are replacing vec(i) with vec(i+1). This is changing our vector and not sorting it. Try to swap places of the two elements.
Second, our first and second if-condition is not changing anything and can thus be left out.
Third, you are only going through our vector once. This will not ensure that the vector is completely sorted. You have to repeat this loop until the vector is fully sorted.
Maybe a look at different sorting algorithms will help you. The one you are tiring to use is called: Bubble sort
This is one possible solution for the problem:
function [sorted] = mySort(vec)
vec = [4 5 2 3];
l = length(vec)-1;
swapped = 1;
while swapped ~= 0
swapped = 0;
for i=1:l
if vec(i)>vec(i+1)
zw = vec(i);
vec(i)=vec(i+1);
vec(i+1)=zw;
swapped = swapped +1;
end
end
sorted = vec;
end
end
Cheers

Categories

Find more on Shifting and Sorting Matrices 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!