Scala中的排序功能运行了很长时间

时间:2016-01-28 03:21:10

标签: scala recursion infinite

我正在尝试在SCALA中编写一个递归函数,它将sin作为一个列表并对其进行排序。

但是,代码似乎运行了很长时间。它甚至没有给我一个错误信息。

def sort(list:List[Int]):List[Int] = list match{

  case Nil => Nil
   case h::t => insert (h, sort(t))
def insert(num:Int, list:List[Int]): List[Int]=list match{
  case Nil => List()
   case head::tail=>
     if(head>=num)
        num::list
     else
       head::insert(num,tail)
   }
 sort(list)
}

1 个答案:

答案 0 :(得分:1)

你有两个问题:

1)您直接从sort函数递归调用sort - 删除sort(list)因为insert已经调用它。这将使其终止。

2)你在其中一个案例中返回一个空列表,而不是用1个元素构建一个列表 - 基本案例是错误的。

此版本有效:

    def sort(list: List[Int]): List[Int] = {
        def insert(num: Int, list: List[Int]): List[Int] = list match {
          case Nil => num :: Nil
          case head::tail =>
            if(head >= num)
              num::list
            else
              head::insert(num, tail)
        }
        list match {
          case Nil => Nil
          case h::t => insert(h, sort(t))
        }
    }