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

30 ビュー (過去 30 日間)
Alexya
Alexya 2022 年 10 月 21 日
回答済み: MisterQuax 2022 年 10 月 21 日
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

回答 (1 件)

MisterQuax
MisterQuax 2022 年 10 月 21 日
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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by