我是Scala的新手并且遇到了这段代码的问题。我在第18/20行遇到了堆栈溢出错误,但我不确定原因。
def quicksort(list : List[Int]) : List[Int] = list match {
case Nil => List()
case x::Nil => List(x)
case x::xs => {
val lesserList = partitionLesser(list.tail, list(0))
val greaterList = partitionGreater(list.tail, list(0))
quicksort(lesserList ::: List(x) ::: greaterList)
}
}
def partitionLesser(list : List[Int], pivot : Int) : List[Int] = list match{
case Nil => List()
case x::Nil => List(x)
case x::xs => {
if(x <= pivot) { x :: partitionLesser(list.tail, pivot) }
else { partitionLesser(list.tail, pivot) }
}
}
def partitionGreater(list : List[Int], pivot : Int) : List[Int] = list match {
case Nil => List()
case x::Nil => List(x)
case x::xs => {
if(x > pivot) { x :: partitionGreater(list.tail, pivot) }
else { partitionLesser(list.tail, pivot)}
}
}
答案 0 :(得分:2)
def quicksort(list : List[Int]) : List[Int] = list match {
case Nil => List()
case x::Nil => List(x)
case x::xs => {
val lesserList = partitionLesser(list.tail, list(0))
val greaterList = partitionGreater(list.tail, list(0))
// quicksort(lesserList ::: List(x) ::: greaterList)
quicksort(lesserList) ::: List(x) ::: quicksort(greaterList)
}
}