【问题标题】:How to implement Insertion Sort in Scala?如何在 Scala 中实现插入排序?
【发布时间】:2015-05-01 12:48:20
【问题描述】:

我在 Scala 中给出了以下代码:

def insertsort (l: List[Int]): List[Int] = {
        if (l == Nil) Nil
        else insert (l.head, insertsort (l.tail))
}

我现在如何实现insert()

【问题讨论】:

  • 显然,这是一个任务。你试过什么。?您需要在哪里插入 l.head? (列表中之前是什么,之后是什么)?将一个条目插入一个空列表的结果是什么?

标签: list scala insert insertion-sort


【解决方案1】:

我将如何进行插入排序:

def insertSort(l: List[Int]): List[Int] = {
  l.foldLeft(List.empty[Int]) { (sorted, i) =>
    val (less, greater) = sorted.partition(_ < i)
    (less :+ i) ++ greater
  }
}

如果您不熟悉 foldLeft,以下是它的工作原理。当我们说 l.foldLeft 时,这意味着我们将为 l 的每个成员(我们想要排序的列表)做一些事情。我们传入一个空列表作为第一个参数,它表示我们已经排序的列表部分(它开始为空,因为我们还没有做任何事情)。对于 foldLeft 的每次迭代,我们将按排序顺序再添加一个列表元素,并以此方式构建我们的解决方案。

第二个参数是一个有两个参数的函数。第一个是累积排序列表,第二个是我们试图添加到排序列表中的 l 中的当前整数。我们将排序后的列表分成两个列表,一个小于当前 int,一个大于/等于。然后我们在中间插入我们的 int 。该函数的返回值成为下一次迭代中的第一个参数(我们称之为“排序”)。

让我们排序 l = List(3, 1, 2)

第一遍:sorted = Nil, i = 3. less 和 greater 都是 Nil。该函数返回 Nil + 3 + Nil,即 List(3),为下一次传递排序。

第二遍:sorted = List(3),i = 1。less = Nil,greater = List(3)。该函数返回 Nil + 1 + List(3),其中 = List(1, 3)。

第三遍:sorted = List(1, 3),i = 2。less = List(1),greater = List(3)。函数返回 List(1) + 2 + List(3) = List(1, 2, 3)。

在我们迭代完所有 l 之后,foldLeft 返回最终的累加值(最后一次迭代的最后一行的值,在我们的例子中:List(1, 2, 3))。

希望有帮助!

【讨论】:

    【解决方案2】:

    看看这个。

    /**
       * Insertion sort algorithm(https://en.wikipedia.org/wiki/Insertion_sort)
       * typically has nested loops with mutable state in imperative style of program
       *
       * Steps of an insertion sort:
       * 3 7 4 9 5 2 6 1
       * 3 7 4 9 5 2 6 1
       * 3 7 4 9 5 2 6 1
       * 3 4 7 9 5 2 6 1
       * 3 4 7 9 5 2 6 1
       * 3 4 5 7 9 2 6 1
       * 2 3 4 5 7 9 6 1
       * 2 3 4 5 6 7 9 1
       * 1 2 3 4 5 6 7 9
       *
       * @param input
       * @return
       */
      def insertionSort(input: List[Int]): List[Int] = {
    
        input.foldLeft(List[Int]())( (acc, element) => {
    
          val (firstHalf, secondHalf) = acc.span(_ < element)
    
          //inserting the element at the right place
          firstHalf ::: element :: secondHalf
        })
      }
    

    这里是source code

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多