【问题标题】:Getting node stack overflow error in R for Quicksort在 R 中获取快速排序的节点堆栈溢出错误
【发布时间】:2017-10-24 17:25:13
【问题描述】:
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 控制台中测试每个命令时它的工作但完整的代码不能完美地工作是代码的逻辑正确还是错误

【问题讨论】:

  • 手动运行几次。您会注意到,有时您使用与输入函数时相同的参数调用快速排序。因此,如果没有任何变化……它最终会调用 quicksort(x, 1, 0) ,然后在函数中的某个地方调用 quicksort(x, 1, 0) ,然后在该函数中的某个地方调用 quicksort(x , 1, 0)...
  • @Dason 我认为是无限递归的问题

标签: r stack-overflow quicksort


【解决方案1】:

将代码修改为

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

【讨论】:

    最近更新 更多