繁体   English   中英

如何在Scala中实现插入排序?

[英]How to implement Insertion Sort in Scala?

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

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

我现在如何实现insert()

这是我进行插入排序的方法:

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)

第一遍:排序= Nil,i =3。越来越少的都是Nil。 该函数返回Nil + 3 + Nil,即List(3),将在下一次传递时进行排序。

第二次通过:已排序= List(3),i =1。更少=无,更大= List(3)。 该函数返回Nil +1 + List(3),即= List(1,3)。

第三遍:已排序= List(1,3),i =2。更少= List(1),更大= List(3)。 函数返回List(1)+ 2 + List(3)= List(1、2、3)。

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

希望有帮助!

看一下这个。

/**
   * 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
    })
  }

这是源代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM