Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Create Array that reorders given values to have smallest first and largest last while maintaining the rest of the array.

조회 수: 1 (최근 30일)
I'm trying to write a program that reorders a given array from a .mat file to have the smallest value first and the largest value last, while preserving the rest of the array.
What I have is:
y = vorder(load('vorder.mat'));
function y=vorder(x)
N = length(x);
y1 = x;
for i = 1:N-1
if y1(i-1) > y1(i)
tmp = y1(i);
y1(i-1) = y1(i);
y1(i) = tmp;
end
end
for i = 2:N-1
if y1(i) < y1(i-1)
tmp = y1(i);
y1(i) = y1(i-2);
y1(i-1) = tmp;
end
end
y = y1;
end
When I run this, it just replicates the exact array x, i'm not sure if it's from the "y = y1" and it's only taking that value or what I'm doing wrong with it.

답변 (1개)

James Tursa
James Tursa 2020년 10월 4일
편집: James Tursa 2020년 10월 5일
That 2nd loop needs to run in reverse order. You need to bubble that smallest number which might be near the back all the way to the front. And you need to ask yourself if your algorithm leaves all of the other elements the same or does it change their order too?

이 질문은 마감되었습니다.

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by