【问题标题】:Is scala sorting stable?scala排序稳定吗?
【发布时间】:2016-05-23 23:52:27
【问题描述】:

Scala 集合有sortBy 方法。那个方法稳定吗?

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

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

【问题讨论】:

    标签: scala sorting collections standard-library


    【解决方案1】:

    是的,它很稳定。来自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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-02
      • 2012-05-16
      • 2015-06-02
      • 2010-09-11
      • 2012-01-03
      • 1970-01-01
      • 2011-06-01
      相关资源
      最近更新 更多