using a for loop to sort a vector without sort or max/min functions
32 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!