0

I am new to Scala and was trying the Selection Sort algorithm. I managed to do a min sort but when I try to do the max sort I get a sorted array but in decreasing order. My code is:

def maxSort(a:Array[Double]):Unit = {
    for(i <- 0 until a.length-1){
            var min = i
                    for(j <- i + 1 until a.length){
                            if (a(j) < a(min)) min = j
            }
    val tmp = a(i)
    a(i) = a(min)
    a(min) = tmp
    }
}

I know that I have to append my result at the end of the array, but how do I do that?

0

2 Answers 2

2

This code will sort the array using the maximum in increasing order:

def maxSort(a:Array[Double]):Unit = {
  for (i <- (0 until a.length).reverse) {
    var max = i
    for (j <- (0 until i).reverse) {
      if (a(j) > a(max)) max = j
    }
    val tmp = a(i)
    a(i) = a(max)
    a(max) = tmp
  }
}

The main issue here is iterating through the array in reverse order, more solutions are provided here: Scala downwards or decreasing for loop?

Please note that Scala is praised for it's functional features and functional approach might be more interesting and "in the style of language". Here are some examples of Selection Sort:

Selection sort in functional Scala

1
  • Thanks for the answer and the reference.
    – Arnab
    Commented May 4, 2016 at 3:36
0

Select Sort in functional style:

  def selectionSort(source: List[Int]) = {
    def select(source: List[Int], result: List[Int]) : List[Int] = source match {
      case h :: t => sort(t, Nil, result, h) 
      case Nil => result
    }
    @tailrec
    def sort(source: List[Int], r1: List[Int], r2: List[Int], m: Int) : List[Int] = source match {
      case h :: t => if( h > m) sort(t, h :: r1, r2, m) else  sort(t, m :: r1, r2, h)
      case Nil =>  select(r1, r2 :+ m)
    }
    select(source, Nil)
  }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.