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

32 Ansichten (letzte 30 Tage)
Alexya
Alexya am 21 Okt. 2022
Beantwortet: MisterQuax am 21 Okt. 2022
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

Antworten (1)

MisterQuax
MisterQuax am 21 Okt. 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

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by