1

Lets say I have 2 matrices,

a = [2,5,3,6]
b = [9,1,8,4]

What I want to do is create a function that sorts A from lowest to highest, and the corresponding values of B hold. I need to do this without using sortrows, however.

Here's my idea at the moment.

function [ out ] = mergesort( a,b )  
c = [a;b]  
d = mergesort(c,:))  
out = [c;b]

Now the ending is where I have a bit of trouble, as the first array is sorted but the second is (obviously) not. Can anyone help me please?

EDIT: Here is my merge sort algorithm.

function [ out ] = mergesort (a)
n=length(a);
if (n==1)
out=a; return
end
out=merge(mergesort(a(1,1:floor(n/2))),...
mergesort(a(1,floor(n/2)+1:n)));
end

EDIT 2: Here is the 'merge' algorithm.

function [ out ] = merge(a,b)
lena = length(a);
lenb = length(b)
out=zeros(1,lena+lenb);
j=1;
k=1;
l=1;
while (j<=lena)&&(k<=lenb))
if (a(1,j)<b(1,k))
out(1,l) = a(1,j); j=j+1; l=l+1;
else
out(1,l) = b(1,k); k=k+1, l=l+1;
end
end
while (j<=lena)
out(1,l) = a(1,j); j=j+1; l=l+1;
end
while (k<=lenb)
out(1,l) = b(1,k); k=k+1;l=l+1;
end
end

2 Answers2

3

This solution does not use sortrows

c=[a;b];
[~,index]=sort(c(1,:));
out=c(:,index);
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • Is there any way to do this without sort? As in I have a function called mergesort which sorts the two out, I just need to align the second row in correspondence. – user3052576 Nov 30 '13 at 21:44
  • Modify your `mergesort` and add a index parameter, similar to the build-in `sort` – Daniel Nov 30 '13 at 21:46
  • Any hints on how to achieve this? I'm guessing that my input value will need to be 2 variables long, but i'm dumbfounded as to how to modify the sort to accommodate for the extra matrix. – user3052576 Nov 30 '13 at 22:05
  • Add a second line to your data `x(2,:)=1:numel(x)`. Move these indices together with your data. For more detailed help, add the code to your question. – Daniel Nov 30 '13 at 23:52
  • Added the sort to the question. merge is another function that merges two sorted row vectors together. – user3052576 Dec 01 '13 at 00:05
  • Please add full code. – Daniel Dec 01 '13 at 01:30
  • Ok i've updated it. Sorry for the delay - I tried again to solve my issue without any luck. – user3052576 Dec 01 '13 at 16:20
2
[asorted,order]=sort(a);
correspondingValuesOfb=b(order)

Sort puts in variable order the reordering done to a. Technically, asorted==a(order).

user2987828
  • 1,116
  • 1
  • 10
  • 33