Scala 插入排序

利用List的方法,代码极简,无需记忆下标移动。

①方法insert将元素x插入到xs,使左边的元素都比x小。

②insert(xs.head, isort(xs.tail)),可以理解为将待排序的List的第一个元素插入到其中①中所说的位置,参数isort(xs.tail)表示此待插入的集合已经有序。

object Test16 {

  def main(args: Array[String]): Unit = {
    val list = List(9, 8, 7, 6, 5, 4, 3, 2, 1)
    val result = insertSort(list)
    println(result)
  }

  def insertSort(xs: List[Int]): List[Int] = if (xs.isEmpty) Nil else insert(xs.head, insertSort(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)

}

模式匹配版

object Test16 {

  def main(args: Array[String]): Unit = {
    val list = List(9, 8, 7, 6, 5, 4, 3, 2, 1)
    val result = insertSort(list)
    println(result)
  }

  def insertSort(xs: List[Int]): List[Int] = xs match {
    case List() => List()
    case y :: ys => insert(y, insertSort(ys))
  }

  def insert(x: Int, xs: List[Int]): List[Int] = xs match {
    case List() => List(x)
    case y :: ys => if (x <= y) x :: xs else y :: insert(x, ys)
  }
  
}

  

原文地址:https://www.cnblogs.com/noyouth/p/14123102.html