Scala中的重排序序列
假设我有一个Seq[Int]。现在我想对序列重新排序,将序列元素0放在它们后面。如何在Scala中简单而高效地完成此操作?它简单而快速:Scala中的重排序序列,scala,sorting,sequence,Scala,Sorting,Sequence,假设我有一个Seq[Int]。现在我想对序列重新排序,将序列元素0放在它们后面。如何在Scala中简单而高效地完成此操作?它简单而快速: Seq(1, -1, 4, 2, -3, 6, -4).partition(_ <= 0) match{ case (smaller, bigger) => smaller ++ bigger } //List(-1, -3, -4, 1, 4, 2, 6) 最简单的: xs.sortBy(_ > 0) 效率略高: xs.grou
Seq(1, -1, 4, 2, -3, 6, -4).partition(_ <= 0) match{
case (smaller, bigger) => smaller ++ bigger
}
//List(-1, -3, -4, 1, 4, 2, 6)
最简单的:
xs.sortBy(_ > 0)
效率略高:
xs.groupBy(_ > 0).toSeq.sortBy(_._1).flatMap(_._2)
更有效的方法是:
xs.partition(_ <= 0) match { case(a,b) => a ++ b }
更有效的方法是直接使用阵列。既然您从Seq[Int]开始,我假设您对速度没有太大压力。或者:
def reorder(xs: Seq[Int]): Seq[Int] =
((_: Seq[Int]) ++ (_: Seq[Int])) tupled xs.partition(_ <= 0)
def reorder(xs: Seq[Int]): Seq[Int] =
((_: Seq[Int]) ++ (_: Seq[Int])) tupled xs.partition(_ <= 0)