Skip to content

Instantly share code, notes, and snippets.

Created February 10, 2016 01:05
Show Gist options
  • Select an option

  • Save anonymous/18ef9692e91443217a09 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/18ef9692e91443217a09 to your computer and use it in GitHub Desktop.
Scala sorting using Ordering[T] compared to direct calls.
def time[A](f: => A): A = {
val s = System.nanoTime
val ret = f
val elapsed = (System.nanoTime - s) / 1e9
println(s"Elapsed: $elapsed")
ret
}
val rnd = new scala.util.Random(42)
val nb = 10000
val scores = (0 until nb).map(x => rnd.nextDouble).toArray
val indices = (0 until nb).toArray
class OrderingByScore extends Ordering[Int] {
def compare(a: Int, b: Int): Int = {
//scores(b).compare(scores(a))
val comp = scores(b) - scores(a)
if (comp > 0) {
1
} else if (comp == 0) {
a - b
} else {
-1
}
}
}
time { (0 to 10000).par.foreach(x => {
scala.util.Sorting.quickSort[Int](indices.take(nb))(new OrderingByScore)
})}
// Elapsed: 30 seconds
def sortArray1(array: Array[Int], left: Int, right: Int, ord: Ordering[Int]) {
if (right <= left) {
return
}
val pivot = array(right)
var p = left
var i = left
while (i < right) {
if (ord.compare(array(i), pivot) > 0) {
if (p != i) {
val tmp = array(p)
array(p) = array(i)
array(i) = tmp
}
p += 1
}
i += 1
}
array(right) = array(p)
array(p) = pivot
sortArray1(array, left, p - 1, ord)
sortArray1(array, p + 1, right, ord)
}
time { (0 to 10000).par.foreach(x => {
sortArray1(indices.take(nb), 0, nb - 1, new OrderingByScore)
})}
// Elapsed: 19 seconds
def sortArray2(array: Array[Int], left: Int, right: Int, ord: OrderingByScore) {
if (right <= left) {
return
}
val pivot = array(right)
var p = left
var i = left
while (i < right) {
if (ord.compare(array(i), pivot) > 0) {
if (p != i) {
val tmp = array(p)
array(p) = array(i)
array(i) = tmp
}
p += 1
}
i += 1
}
array(right) = array(p)
array(p) = pivot
sortArray2(array, left, p - 1, ord)
sortArray2(array, p + 1, right, ord)
}
time { (0 to 10000).par.foreach(x => {
sortArray2(indices.take(nb), 0, nb - 1, new OrderingByScore)
})}
// Elapsed: 1.85 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment