微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scala库方法Vector.sorted使用什么算法?

我一直在看 Scala documentation,但到目前为止我没有找到我的问题的答案,即该方法使用了什么排序算法

scala.collection.immutable.Vector.sorted

该文档说它是一种稳定的排序,但不是实际使用的算法.它是合并排序吗?

解决方法

已排序的方法在SeqLike中实现,并且似乎使用java.util.Arrays.sort进行排序.它从向量构建一个数组,然后调用Arrays.sort,然后将其转换回来.根据 Java 6 documentation,它因此使用quicksort:

The sorting algorithm is a tuned quicksort,adapted from Jon L. Bentley and M. Douglas McIlroy’s “Engineering a Sort Function”,Software-Practice and Experience,Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.

对于Java 7,该算法似乎有所改变(再次引用the docs):

The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy,Jon Bentley,and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance,and is typically faster than Traditional (one-pivot) Quicksort implementations.

Scala的SeqLike#sorted source (taken from GitHub)

/** 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 arr = new ArraySeq[A](len)
    var i = 0
    for (x <- this.seq) {
      arr(i) = x
      i += 1
    }
    java.util.Arrays.sort(arr.array,ord.asInstanceOf[Ordering[Object]])
    val b = newBuilder
    b.sizeHint(len)
    for (x <- arr) b += x
    b.result
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐