Borrar filtros
Borrar filtros

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

21 visualizaciones (últimos 30 días)
Alexya
Alexya el 21 de Oct. de 2022
Respondida: MisterQuax el 21 de Oct. de 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

Respuestas (1)

MisterQuax
MisterQuax el 21 de Oct. de 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

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by