Specialized sorting of array while preserving order

how can i sort an array (of even number of elements) so the elements on the left side are smaller than the elements on the right side but without changing the original order of the elements in the array?
for example:
a = [19 21 12 -15 18 1 22 11];
r = [12 -15 1 11 19 21 18 22];
12 is prior to -15 in the original array and so it is in the result.
another example:
a = [8 4 2 6 3 1 9 10];
r = [ 4 2 3 1 8 6 9 10];

댓글 수: 1

Thomas
Thomas 2012년 11월 21일
편집: Thomas 2012년 11월 21일
Why is 12 first. The results seems to be random.
but 4 is larger than 2..

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt Fig
Matt Fig 2012년 11월 21일
편집: Matt Fig 2012년 11월 21일
% Your original array
a = [19 21 12 -15 18 1 22 11];
% Now the method:
L = length(a)/2;
[~,J] = sort(a); % For older MATLAB vers,[J,J] = sort(a);
[~,J] = sort(J);
r = [a(J<=L) a(J>L)]

댓글 수: 4

Zaza
Zaza 2012년 11월 21일
thanks Matt. it works perfect. can i get an explanation of lines 3-4?
Matt Fig
Matt Fig 2012년 11월 21일
편집: Matt Fig 2012년 11월 21일
Hello Zaza, I am afraid the best explanation I can give you would be to have you just look at the help for SORT and look at the outputs. To get a better understanding, look at all the outputs (after reading the help for SORT!):
L = length(a)/2;
[I,J] = sort(a) % Look at these: compare to a
[K,M] = sort(J) % I(M) is a
r = [a(M<=L) a(M>L)]
Zaza
Zaza 2012년 11월 21일
i read the help of sort but i still don't feel comfortable with that...
can you give me please a simple step-by-step ex.? it would be very helpful for me...
Matt Fig
Matt Fig 2012년 11월 21일
편집: Matt Fig 2012년 11월 21일
Zaza, it seems you already have a step-by-step example! Perhaps this will help. Here is another (preferable) way of solving the problem:
L = length(a)/2;
[~,J] = sort(a);
J(J) = 1:L*2;
r = [a(J<=L) a(J>L)]
Now have a look at Loren's blog entry on this method:

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2012년 11월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by