scala - Scala排序是否稳定?

标签 scala sorting collections standard-library

Scala 集合有 sortBy方法。这种方法稳定吗?

def sortList(source : List[Int]) : List[Int] =
  source.sortBy(_ % 2)

这个例子会一直保持秩序吗?

最佳答案

是的,它很稳定。来自Scala源代码的引用:

https://github.com/scala/scala/blob/2.11.x/src/library/scala/collection/SeqLike.scala#L627

def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = sorted(ord on f)

/** Sorts this $coll according to an Ordering.
 *
 *  The sort is stable. That is, elements that are equal (as determined by
 *  `lt`) appear in the same order in the sorted sequence as in the original.
 *
 *  @see [[scala.math.Ordering]]
 *
 *  @param  ord the ordering to be used to compare elements.
 *  @return     a $coll consisting of the elements of this $coll
 *              sorted according to the ordering `ord`.
 */
def sorted[B >: A](implicit ord: Ordering[B]): Repr = {
  val len = this.length
  val b = newBuilder
  if (len == 1) b ++= this
  else if (len > 1) {
    b.sizeHint(len)
    val arr = new Array[AnyRef](len)  // Previously used ArraySeq for more compact but slower code
    var i = 0
    for (x <- this) {
      arr(i) = x.asInstanceOf[AnyRef]
      i += 1
    }
    java.util.Arrays.sort(arr, ord.asInstanceOf[Ordering[Object]])
    i = 0
    while (i < arr.length) {
      b += arr(i).asInstanceOf[A]
      i += 1
    }
  }
  b.result()
}

关于scala - Scala排序是否稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369243/

相关文章:

scala - 刚刚下载了Scala Lift聊天应用,按照说明运行,但是失败了

java - 使用 Java 8 Streams API 打乱整数列表

Java集合查询

Java 流 : divide into two lists by boolean predicate

Scala方法对 map 产生副作用并返回它

java - Spring:注入(inject) Scala 列表

c# - 将项目添加到 List<> 排序吗?

java - 如何在 Java 中实现多线程 MergeSort

sorting - HeapSort 与 MergeSort 空间复杂度

c# - 在 C# 中将 IEnumerable<T> 转换为 List<T> 的最快方法