Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Scala: what is the most appropriate data structure for sorted subsets?
- val a = Vector( 9,2,6,1,7,5,2,6,9 ) // just an example
- val f : (Int)=>Double = (n)=>n // evaluation function
- val b = a.sortBy( f ).take( N ) // sort, then clip
- def firstK[A](xs: Seq[A], k: Int)(implicit ord: Ordering[A]) = {
- val q = new scala.collection.mutable.PriorityQueue[A]()(ord.reverse)
- val (before, after) = xs.splitAt(k)
- q ++= before
- after.foreach(x => q += ord.max(x, q.dequeue))
- q.dequeueAll
- }
- scala> firstK(Vector(9, 2, 6, 1, 7, 5, 2, 6, 9), 4)
- res14: scala.collection.mutable.Buffer[Int] = ArrayBuffer(6, 7, 9, 9)
Add Comment
Please, Sign In to add comment