Debugging 阶统计量

Debugging 阶统计量,debugging,scala,Debugging,Scala,我刚刚开始为我正在学习的一个算法类编写代码,我仍然在学习Scala的基础知识(而且经常出错)。任务是创建一个程序来计算数组的第i阶统计量。我的问题是我在下面写的编译和运行,从值[Array]中打印“Selecting element”+“which+”,然后暂停。没有错误消息。我确信下面的代码中有几个错误。为了充分披露,这是一个家庭作业。谢谢你的帮助 编辑:谢谢你的提示,我编辑了一些东西。我现在认为select正在查看越来越小的数组部分,但代码仍然不起作用。现在,它在大约25%的时间里吐出正确的

我刚刚开始为我正在学习的一个算法类编写代码,我仍然在学习Scala的基础知识(而且经常出错)。任务是创建一个程序来计算数组的第i阶统计量。我的问题是我在下面写的编译和运行,从值[Array]中打印“Selecting element”+“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))
  }
}
对象hw3v2{
// 
//分割
// 
//这是用于分区的代码
//我们的阵型,重新布置
// 
def分区(a:Array[Int],b:Int,c:Int):Int={
val x:Int=a(c)
变量i:Int=b

对于(j我恳求你,试着这样写:

def partition(a: Array[Int], b: Int, c: Int): Int = {
  val x: Int = a(c)
  var i: Int = b - 1

  for (j <- b to c - 1)
    if (a(j) <= x) {
      i += 1
      val hold = a(i)
      a(i) = a(j)
      a(j) = hold
    }

  a(i + 1) = a(c)
  a(c) = a(i + 1)
  i + 1
}

def select(i: Int, a: Array[Int]): Int =
  if (a.length <= 1)
    a(0)
  else {
    val q = partition(a, 0, a.length - 1)
    if (i <= q)
      select(i, a)
    else
      select(i - q, a)
  }

def main(args: Array[String]) {
  val which = args(0).toInt

  printf("Selecting element %s from amongst the values %s%n".format(which, args.mkString(", ")))

  val values = args map(_.toInt)
  printf("%nb ==> %d%n", select(which, values))
}
def分区(a:Array[Int],b:Int,c:Int):Int={
val x:Int=a(c)
变量i:Int=b-1

对于(j您在
select
中的退出条件是数组
a
的长度必须小于或等于1。但是我看不到任何东西会改变数组的长度。因此,对
select
的递归调用无限循环。我只能猜测:因为您的目标似乎是
select
操作每次在不同的数组上执行时,必须将修改后的数组作为输入传递。因此,我猜想
分区
应该同时返回
Int
和修改后的
数组

更新 如果“ith order statistic”是指数组中的“ith”最小元素,为什么不执行以下操作

a.sorted.apply(i)

你能给出一个输入和预期输出的例子吗?也许你想要像
Seq(3,1,5,2,1)。排序。应用(k)
序列的第k顺序统计?哎呀,刚才看到这个注释有点太晚了。我也猜这是OP想要的。。。