Created
April 29, 2012 18:25
-
-
Save non/2552447 to your computer and use it in GitHub Desktop.
Example of sorting list of lists
This file contains 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 annotation.tailrec | |
import scala.math.Ordering | |
import scala.util.Random | |
class ListOrdering extends Ordering[List[Int]] { | |
@tailrec final def compare(as:List[Int], bs:List[Int]) = (as, bs) match { | |
case (Nil, Nil) => 0 | |
case (Nil, _) => -1 | |
case (_, Nil) => 1 | |
case (a::as, b::bs) if a < b => -1 | |
case (a::as, b::bs) if b < a => 1 | |
case (a::as, b::bs) => compare(as, bs) | |
} | |
} | |
object Test { | |
def main(args:Array[String]) { | |
val m = 10000 // # of sublists | |
val n = 50 // # of items per sublist | |
val o = 1000 // range of int values in each sublist | |
def makeInt() = scala.math.abs(Random.nextInt % o).toInt | |
def makeList() = (0 until n).toList.map(i => makeInt) | |
def makeLists() = (0 until m).toList.map(i => makeList) | |
val data = makeLists() | |
implicit val listOrder = new ListOrdering() | |
val t0 = System.currentTimeMillis() | |
val data2 = data.sorted | |
val t = System.currentTimeMillis() - t0 | |
println("sorted %d lists of length %d in %d ms" format (m, n, t)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment