我刚开始为我正在学习的算法课程编写代码,而且我仍在大量学习 Scala 的基础知识(并且经常搞砸)。任务是创建一个计算数组的第 i 阶统计量的程序。我的问题是我在下面编写的编译和运行,打印“从值 [Array] 中选择元素“+which+””,然后停止。没有错误消息。我确定下面的代码中有几个错误。为了充分披露,这是一项家庭作业。我很感激任何帮助。
编辑:感谢您的提示,我编辑了一些东西。我现在认为 select 正在查看数组的越来越小的部分,但代码仍然不起作用。现在它在大约 25% 的时间里吐出正确答案,其余时间做同样的事情。
object hw3v2 {
//
// partition
//
// this is the code that partitions
// our array, rearranging it in place
//
def partition(a: Array[Int], b: Int, c: Int): Int = {
val x:Int = a(c)
var i:Int = b
for (j <- b to c-1)
if (a(j) <= x) {
i += 1
a(i) = a(j)
a(j) = a(i)
}
a(i+1) = a(c)
a(c) = a(i+1)
i + 1
}
def select(a: Array[Int], p: Int, r: Int, i: Int): Int = {
if (p == r)
a(0)
else {
val q = partition(a, p, r)
val j = q - p + 1
if (i <= j)
select(a, p, q, i)
else
select(a, q+1, r, i-j)
}
}
def main(args: Array[String]) {
val which = args(0).toInt
val values: Array[Int] = new Array[Int](args.length-1);
print("Selecting element "+which+" from amongst the values ")
for (i <- 1 until args.length) {
print(args(i) + (if (i<args.length-1) {","} else {""}));
values(i-1) = args(i).toInt;
}
println();
println("==> "+select(values, 0, values.length-1, which))
}
}