Skip to content

Commit 4fad817

Browse files
author
Antoine Brunner
committed
Add mergeSort benchmark to tupleOps.scala
1 parent 34adaad commit 4fad817

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

bench-run/src/main/scala/dotty/tools/benchmarks/tuples/TupleOps.scala

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package dotty.tools.benchmarks.tuples
22

33
import org.openjdk.jmh.annotations._
4+
import scala.util.Random
45

56
@State(Scope.Thread)
67
class TupleOps {
78
var tuple1: Tuple = _
89
var tuple2: Tuple = _
10+
var tuple3: Tuple = _
911

1012
@Setup
1113
def setup(): Unit = {
@@ -16,6 +18,8 @@ class TupleOps {
1618
tuple2 = ()
1719
for (i <- 1 until 10)
1820
tuple2 = s"elem$i" *: tuple2
21+
22+
tuple3 = Tuple.fromArray(Random.shuffle(1 to 15).toArray)
1923
}
2024

2125
def tupleFlatMap(tuple: Tuple, f: [A] => A => Tuple): Tuple = {
@@ -34,6 +38,22 @@ class TupleOps {
3438
tailRecReverse(tuple, ())
3539
}
3640

41+
def tupleMerge(tuple1: Tuple, tuple2: Tuple): Tuple = (tuple1, tuple2) match {
42+
case (_, ()) => tuple1
43+
case ((), _) => tuple2
44+
case (x *: xs, y *: ys) =>
45+
if (x.asInstanceOf[Int] <= y.asInstanceOf[Int]) x *: tupleMerge(xs, tuple2)
46+
else y *: tupleMerge(tuple1, ys)
47+
}
48+
49+
def tupleMergeSort(tuple: Tuple): Tuple =
50+
if (tuple.size <= 1) tuple
51+
else {
52+
val (tuple1, tuple2) = tuple.splitAt(tuple.size / 2)
53+
val (sorted1, sorted2) = (tupleMergeSort(tuple1), tupleMergeSort(tuple2))
54+
tupleMerge(sorted1, sorted2)
55+
}
56+
3757
@Benchmark
3858
def reverse(): Tuple = {
3959
tupleReverse(tuple1)
@@ -43,4 +63,9 @@ class TupleOps {
4363
def flatMap(): Tuple = {
4464
tupleFlatMap(tuple2, [A] => (x: A) => (x, x))
4565
}
66+
67+
@Benchmark
68+
def mergeSort(): Tuple = {
69+
tupleMergeSort(tuple3)
70+
}
4671
}

0 commit comments

Comments
 (0)