One easy way to obtain indices from any sorting algorithm is to "hang" some indices onto the data before sorting, and apply exactly the same permutations to those indices as are applied to the data themselves. I wrapped your function in another one to make this a bit easier to implement:
function [out,idx] = quicksort(vec)
assert(isrow(vec),'Input must be a row vector')
Z = qsRecFun([vec;1:numel(vec)]);
out = Z(1,:);
idx = Z(2,:);
end
function Sm = qsRecFun(M)
N = size(M,2);
if N<2
Sm = M;
else
jj = 1;
kk = 1;
Lm = [];
Rm = [];
X = fix(N/2);
P = M(:,X);
for ii = [1:X-1,X+1:N]
if M(1,ii)<P(1)
Lm(:,jj) = M(:,ii);
jj = jj+1;
else
Rm(:,kk) = M(:,ii);
kk = kk+1;
end
end
Lm = qsRecFun(Lm);
Rm = qsRecFun(Rm);
Sm = [Lm,P,Rm];
end
end
And checking the output against that of MATLAB's sort:
>> V = randi(9,1,7)
V =
9 5 3 8 1 6 2
>> [Y,X] = quicksort(V)
Y =
1 2 3 5 6 8 9
X =
5 7 3 2 6 4 1
>> [Y,X] = sort(V)
Y =
1 2 3 5 6 8 9
X =
5 7 3 2 6 4 1
Note that you could also improve the code by using logical indexing, although this would look less like the naive algorithm itself.
Best Answer