function select = sortcluster(v)
%
% select = sortcluster(v)
%
[~,idx] = sort(v,'descend');
idxx = idx;
n = length(v);
select = false(n); % maximum size
i = n;
ns = 0;
if (all(1:idx(n) == idx(n-idx(n)+1:n)))
% fist elements already sorted
  i = n-idx(n);
else
  i = n;
end
while (i >= 1)
  value = v(idx(i));      
  for j = i:-1:1
    if (v(idx(j)) == value)
      idxx(idx<idx(j)) = idxx(idx<idx(j))+1;
    else
      j = j+1;	    
      break
    end
  end
  if ((ns >=1 ) && select(ns,idxx(j)))
% try to compress select
    for k = idxx(j)-1:-1:1
      if (~select(ns,k))
	select(ns,k) = true;
	break
      end
    end
  else
    ns = ns+1;
    select(ns,idxx(j)) = true;
  end
  i = j-1;
end    
select = select(1:ns,:);
