0

我刚开始为我正在学习的算法课程编写代码,而且我仍在大量学习 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))
  }
}
4

2 回答 2

1

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

更新

如果“第 i 个顺序统计”是指数组中的“第 i 个”最小元素,为什么不直接执行以下操作?

a.sorted.apply(i)
于 2013-02-22T07:48:15.313 回答
1

我恳求你,试着写更多这样的:

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))
}

据我所知,这相当于您的原始代码。

于 2013-02-22T04:59:53.350 回答