# Specialized sorting of array while preserving order

3 views (last 30 days)
Zaza on 21 Nov 2012
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 CommentShowHide None
Thomas on 21 Nov 2012
Edited: Thomas on 21 Nov 2012
Why is 12 first. The results seems to be random.
but 4 is larger than 2..

Matt Fig on 21 Nov 2012
Edited: Matt Fig on 21 Nov 2012
% 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)]
Matt Fig on 21 Nov 2012
Edited: Matt Fig on 21 Nov 2012
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: