3

I'm attempting to convert a Selection sort from Java to Scala and im unsure how to convert this loop to Scala :

for (int j = i + 1; j < N; j++)

Here is a larger Java code sample and its Scala equivalent :

Java :

sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
   int min = i
   for (int j = i + 1; j < N; j++)
}

Scala :

  def sort(a : Array[Ordered[Any]]) = {
    var N = a.length

    for (i <- 0 until N) {
        var min = i

        for(j <- until j < N){

        }
    }

  }

How do I convert the inner loop to Scala ?

for (int j = i + 1; j < N; j++)

I dont know how to do assignment while iterating...

4

3 回答 3

7

干得好:

def sort(a : Array[Ordered[Any]]) = {
    val N = a.length

    for (i <- 0 until N) {
        var min = i

        for(j <- i + 1 until N){

        }
    }

  }

此外,在 Scala 中,您可以在内部定义值以进行理解,并将多个块合并为一个:

def sort(a : Array[Ordered[Any]]) = {
        val n = a.length

        for(i <- 0 until n; min = i; j <- i + 1 until n) { // min here is val, not var
          // do something with i, j and min
        }
}

有时,这可能会导致代码更清晰

于 2013-04-23T20:02:48.657 回答
3

不幸的是,Scala 的循环标准非常慢(尤其是旧版本)。

另一种选择是经典的 while 循环,即使它不是很清楚:

  def sort(a : Array[Ordered[Any]]) = {
    val N = a.length

    var i = 0;
    while (i < N) {
        var min = i

        var j = i + 1;
        while (j < N) {
          j += 1;
        }
        i += 1;
    }

}

或尾递归函数:

  def sort(a : Array[Ordered[Any]]) = {
    val N = a.length

    def l1(i: Int){
      def l2(j: Int, min: Int){
        if (j < N) 
          l2(j+1, min)
      }
      if (i < N) {
         l2(i+1, i);
         l1(i+1);
      }
    }
}

或者 spire 的 cfor:

  def sort(a : Array[Ordered[Any]]) = {
    val N = a.length

    cfor(0)(_ < N, _ + 1) { i => 
        var min = i
        cfor(i+1)(_ < N, _ + 1) { j => 
        }
    }

}
于 2013-04-23T20:10:33.353 回答
0

使用 for 循环(不完全是功能/惯用的 scala 方式)进行迭代将非常类似于 java 代码。这会让你度过难关。

def sort(a: Array[Comparable]) {
  val N = a.length
  for (
    i <- 0 until N;
    min = i;
    j <- (i + 1) until N
  ) {
    // more code..
  }
}

这是您的Java代码供参考:

sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
   int min = i
   for (int j = i + 1; j < N; j++)
}
于 2013-04-24T00:56:16.907 回答