我需要使用合并排序来计算反转次数:
object Example {
def msort(xs: List[Int]): List[Int] = {
def merge(left: List[Int], right: List[Int]): Stream[Int] = (left, right) match {
case (x :: xs, y :: ys) if x < y => Stream.cons(x, merge(xs, right))
case (x :: xs, y :: ys) => Stream.cons(y, merge(left, ys))
case _ => if (left.isEmpty) right.toStream else left.toStream
}
val n = xs.length / 2
if (n == 0) xs
else {
val (ys, zs) = xs splitAt n
merge(msort(ys), msort(zs)).toList
}
}
msort(List(8, 15, 3))
}
我想我必须把它算在行中(其中y < y
,第二行match
)
case (x :: xs, y :: ys) => Stream.cons(y, merge(left, ys))
但是,当我尝试时,我失败了。
我怎么做?
更新:
带有累加器的版本:
def msort(xs: List[Int]): List[Int] = {
def merge(left: List[Int], right: List[Int], inversionAcc: Int = 0): Stream[Int] = (left, right) match {
case (x :: xs, y :: ys) if x < y => Stream.cons(x, merge(xs, right, inversionAcc))
case (x :: xs, y :: ys) => Stream.cons(y, merge(left, ys, inversionAcc + 1))
case _ => if (left.isEmpty) right.toStream else left.toStream
}
val n = xs.length / 2
if (n == 0) xs
else {
val (ys, zs) = xs splitAt n
merge(msort(ys), msort(zs)).toList
}
}
我如何轻松返回inversionAcc
?我想,我只能像这样将它作为元组的一部分返回:
def merge(left: List[Int], right: List[Int], invariantAcc: Int = 0): (Stream[Int], Int)
不过,看起来不太好。
更新2:
它实际上并没有正确计算,我找不到错误在哪里。