Skip to content

Instantly share code, notes, and snippets.

@stevej
Created July 30, 2009 22:51
Show Gist options
  • Save stevej/158982 to your computer and use it in GitHub Desktop.
Save stevej/158982 to your computer and use it in GitHub Desktop.
multi-way-merge as a tail recursive function in Scala
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