在Quicksort的R中获取节点堆栈溢出错误

时间:2017-10-24 17:25:13

标签: r stack-overflow quicksort

quicksort <- function(x, s, e) {
    p = s
    i = 0
    j = 0
    for (k in 1:length(x)) {
        if (x[p] < x[k]) 
            i = k
    }
    if (!i) 
        i = e
    for (k in length(x):1) {
        if (x[p] > x[k]) 
            j = k
    }
    if (!j) 
        j = s
    if (i < j) {
        t = x[i]
        x[i] = x[j]
        x[j] = t
    } else {
        t = x[j]
        x[j] = x[p]
        x[p] = t
        quicksort(x, s, j - 1)
        quicksort(x, j + 1, e)
    }
    x
}
quick = function(x) {
    quicksort(x, 1, length(x))
}

当我使用Vector运行此i R控制台时出现错误

> x<-c(4,47,480,15,0,147,1,56862,12)
> quick(x)
Error: node stack overflow

它在R控制台中测试每个命令时工作但是完整的代码不能正常工作是代码的逻辑正确或错误

1 个答案:

答案 0 :(得分:0)

将代码修改为

quicksort<-function(x){
if(length(x)<=1)return(x)
p<-x[1]
therest<-x[-1]
i<-therest[therest<p]
j<-therest[therest>p]
i<-quicksort(i)
j<-quicksort(j)
return(c(i,p,j))
}

现在它正常工作控制台响应为

> x<-c(4,47,480,15,0,147,1,56862,12)
> quicksort(x)
[1]     0     1     4    12    15    47   147   480 56862

问题中的代码是从C ++实现的,但答案中的代码是直接R