您可以通过在每个函数调用中传递整个向量以及“start”和“end”参数来描述您当前正在排序的向量切片。这是我第一次尝试这样做。也许你可以写一个更优雅的版本?
qs<-function(vec,start=1,finish=length(vec)) {
if (finish>start) {
pivot<-vec[start]
N<-length(vec)
window<-((1:N)>=start) & ((1:N)<=finish)
low_part<-vec[(vec<pivot) & window]
mid_part<-vec[(vec==pivot) & window]
high_part<-vec[(vec>pivot) & window]
if (start>1) cat(vec[1:(start-1)],"| ")
cat(low_part,">>>",mid_part,"<<<",high_part)
if (finish<N) cat(" |",vec[(finish+1):N])
cat("\n")
vec[window]<-c(low_part,mid_part,high_part)
if (length(low_part)>0) {
low_top<-start+length(low_part)-1
vec[start:low_top]<-qs(vec,start,low_top)[start:low_top]
}
if (length(high_part)>0) {
high_bottom<-finish-length(high_part)+1
vec[high_bottom:finish]<-qs(vec,high_bottom,finish)[high_bottom:finish]
}
}
return(vec)
}
qs(sample(1:30,replace=TRUE))