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...

3 Answers 3

7

Here you go:

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

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

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

        }
    }

  }

Moreover, in Scala you can define values inside for comprehension, and merge multiple blocks into one:

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

Sometimes, this may lead to cleaner code

Sign up to request clarification or add additional context in comments.

Comments

3

Unfortunately, the standard for loops are quite slow on Scala (especially with older version).

An alternative is the classical while loop, even if it is not so clear:

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

}

Or tail recursive functions:

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

Or the cfor of spire:

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

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

}

2 Comments

@BeniBela by 'standard for loops' are you including '.foreach' ?
0

Using for loops (not exactly a functional/idiomatic scala way) for iterating will closely resemble the java code. This will get you through.

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

Here's your java code for reference:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.