Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala中的重排序序列_Scala_Sorting_Sequence - Fatal编程技术网

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[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.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)