function [Y,I] = sort_q(X,Q)
% [Y] = SORT_Q(X,Q) sorts vector X in ascending order finding the Q
%       smallest elements
% [Y,I] = SORT_Q(X,Q) also returns an index vector of the Q smallest
% elements
%
% John Wilkin 12 Feb 96

if nargin == 1
  Q = length(X);
else
  Q = min([Q; length(X)]);
end

unsorted = X;
biggest = max(unsorted)+1;
I = [];

for i=1:Q
  next = min(find(unsorted==min(unsorted)));
  I = [I; next];
  unsorted(next) = biggest;
end
Y = X(I);
