【问题标题】:Insertion sort not working in my code written in Scala插入排序在我用 Scala 编写的代码中不起作用
【发布时间】:2018-07-26 13:26:55
【问题描述】:

我正在编写一个函数来执行插入排序。在编写代码时,我再次得到与输出相同的列表。

def insertionSort(xs: List[Int]): List[Int] =
{
  if (xs.isEmpty) Nil
  else insert(xs.head, xs.tail)
}

def insert(x: Int, xs: List[Int]): List[Int] =
{
  if (xs.isEmpty || x <= xs.head) x :: xs
  else xs.head :: insert(x, xs.tail)
}

谁能告诉我哪里出错了。

【问题讨论】:

标签: scala insertion-sort


【解决方案1】:

我猜你的函数中缺少一个小的递归调用。请参考下面的代码。

def insertionSort(xs: List[Int]): List[Int] =
{
  if (xs.isEmpty) Nil
  else insert(xs.head, insertionSort(xs.tail))
}


def insert(x: Int, xs: List[Int]): List[Int] =
{
  if (xs.isEmpty || x <= xs.head) x :: xs
  else xs.head :: insert(x, xs.tail)
}

我想现在应该可以了。

【讨论】:

  • /* HERE ---&gt; */ insertionSort(xs.tail) /* &lt;--- HERE */ 这样的东西会起作用;)
  • 无论如何。我已经完全删除了它@AndreyTyukin
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多