Created
March 18, 2014 14:28
-
-
Save yyuu/9621175 to your computer and use it in GitHub Desktop.
quick sort with using scala.concurrent.forkjoin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent.forkjoin.ForkJoinPool | |
import scala.concurrent.forkjoin.RecursiveTask | |
object Main { | |
def main(args: Array[String]) { | |
val pool = new ForkJoinPool() | |
println(s"${Thread.currentThread.getId}: unsorted=" + args.mkString(", ")) | |
val sorted = pool.invoke(new QuickSortingTask(args)) | |
println(s"${Thread.currentThread.getId}: sorted=" + sorted.mkString(", ")) | |
} | |
} | |
class QuickSortingTask(data: Seq[String]) extends RecursiveTask[Seq[String]] { | |
override def compute(): Seq[String] = { | |
println(s"${Thread.currentThread.getId}: data=" + data.mkString(", ")) | |
if (data.length < 2) { | |
data | |
} else { | |
val pivot = data.head | |
val unsorted = data.tail | |
val lhs = new QuickSortingTask(unsorted.filter(_ < pivot)) | |
val rhs = new QuickSortingTask(unsorted.filter(_ >= pivot)) | |
rhs.fork | |
lhs.invoke ++ Seq(pivot) ++ rhs.join | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment