Created
July 30, 2009 22:51
-
-
Save stevej/158982 to your computer and use it in GitHub Desktop.
multi-way-merge as a tail recursive function in Scala
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
trait Merge { | |
def m_way_merge(out: List[Int], xs: List[List[Int]]): List[Int] = { | |
val arrays = xs.remove(_ == Nil) | |
if (arrays.isEmpty) { | |
out | |
} else { | |
val idx: Int = arrays.findIndexOf((xs: List[Int]) => xs.head == arrays.map(_.head).sort(_ < _).head) | |
m_way_merge(out ::: List(arrays(idx).head), arrays.slice(0, idx) ::: arrays.slice(idx + 1, arrays.length) ::: List(arrays(idx).tail)) | |
} | |
} | |
def m_way_merge(xs: List[List[Int]]): List[Int] = m_way_merge(Nil, xs) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment