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?

Arnab
  • 1,037
  • 3
  • 16
  • 31

2 Answers2

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

ZbyszekKr
  • 512
  • 4
  • 15
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)
  }