topK<-function(x,K)
{
n<-length(x);
l<-sample(1:n,1);
pivot<-x[l];
if(n<K | n==K) return(x);
idx<-c((1:n)[x>pivot],(1:n)[x==pivot]);
m<-length(idx);
if(m==n) { if(max(x) == min(x)) return(x[1:K]);}
if(m>K) { return(topK(x[idx],K));}
else if(m==K) { return(x[idx]);}
else
{
zL<-topK(x[-idx],(K-m));
return(c(x[idx],zL));
}
}