【问题标题】:Groovy qSort and Filter implementations giving stack overflow errorGroovy qSort 和 Filter 实现给出堆栈溢出错误
【发布时间】:2015-03-25 10:14:45
【问题描述】:

这是我尝试使用的 Groovy 中过滤器的实现。

def filter(list, p) {
    if (list.size() == 0) { return list }
    if (p(list.head())) {
        [] + list.head() + filter(list.tail(), p)
    } else {
        filter(list.tail(), p)
    }
}

这是我尝试使用的快速排序算法的实现。

def qSort(list) {
    if ( list.size() <= 1 ) {
        return list
    } else {
        def pivot = list[(int)list.size() / 2]
        def sorted = []
        sorted += qSort(filter(list, { it < pivot}))
        sorted += qSort(filter(list, { it == pivot})) 
        sorted += qSort(filter(list, { it > pivot })) 
    }
}

这是我要排序的列表,比较随意。

def list = [5, 3, 2, 1, 8, 4, 5, 8, 23, 4, 6, 8, 3, 23, 76, 8, 9, 2, 2, 1, 1, 2]

我收到此错误:

Exception in thread "main" java.lang.StackOverflowError
at java.lang.Math.getExponent(Math.java:1310)
at java.lang.StrictMath.floorOrCeil(StrictMath.java:355)
at java.lang.StrictMath.ceil(StrictMath.java:321)
at java.lang.Math.ceil(Math.java:405)
at java.math.BigDecimal.divide(BigDecimal.java:1608)
at org.codehaus.groovy.runtime.typehandling.BigDecimalMath.divideImpl(BigDecimalMath.java:62)
at org.codehaus.groovy.runtime.typehandling.IntegerMath.divideImpl(IntegerMath.java:46)
at org.codehaus.groovy.runtime.dgmimpl.NumberNumberDiv$NumberNumber.invoke(NumberNumberDiv.java:320)

【问题讨论】:

  • (int)(list.size() / 2)。 size 已经是一个 int。或者只是list.size()&gt;&gt;1
  • 改变不做任何事情,如果我删除类型转换为 int 我得到Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.getAt() is applicable for argument types: (java.math.BigDecimal) values: [11]
  • 这是什么 groovy 版本? stackoverflow 在代码中,但不适用于 2.4 的强制转换/除法/...问题。
  • sorted += qSort(filter(list, { it == pivot})) -- 导致问题的行
  • 如果没有重复元素,看起来代码工作正常。所以如果有重复代码需要处理。

标签: function recursion groovy functional-programming stack-overflow


【解决方案1】:

当你有一个n 数字列表(其中n &gt; 1)都等于枢轴时,它会陷入困境。

如果你改变:

if ( list.size() <= 1 ) {

收件人:

if ( list.unique(false).size() <= 1 ) {

它会起作用的......不过可能会有一个不那么“骇人听闻”的解决方案

【讨论】:

  • 简单而完美的改变。
猜你喜欢
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 2014-04-10
  • 2014-01-26
  • 2019-02-16
  • 2011-09-10
相关资源
最近更新 更多