Skip to content

Instantly share code, notes, and snippets.

@Lytol
Created November 4, 2009 06:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Lytol/225870 to your computer and use it in GitHub Desktop.
Save Lytol/225870 to your computer and use it in GitHub Desktop.
Selection sort implementation in Scala
// Inmperative version
//
def selectionSort(list: Array[Int]): Unit {
def swap(list: Array[Int], i: Int, j: Int) {
var tmp = list(i)
list(i) = list(j)
list(j) = tmp
}
var i = 0
while(i < (list.length - 1)) {
var min = i
var j = i + 1
while (j < list.length) {
if(list(j) < list(min)) {
min = j
}
j += 1
}
swap(list, i, min)
i += 1
}
}
// Functional / Recursive version
//
def selectionSort2(list: List[Int]): List[Int] = {
if(list.length == 1) list
else {
// Pseudo code
// list.min :: selectionSort2(list.everything_but_min)
}
}
@pangiole
Copy link

Even though, when coding Scala, I'm used to prefer functional programming style (via combinators or recursion) over imperative style (via variables and iterations), THIS TIME, for this specific problem, old school imperative nested loops result in simpler code for the reader. I don't think falling back to imperative style is a mistake for certain classes of problems (such as sorting algorithms which usually transform the input buffer (like a procedure) rather than resulting to a new sorted one

My solution on https://github.com/angiolep/algorithms

@shankarshastri
Copy link

shankarshastri commented Apr 19, 2018

def selectionSort(list:List[Int]):List[Int] = {
  @tailrec
  def selectSortHelper(list:List[Int], accumList:List[Int] = List[Int]()): List[Int] = {

    list match {
      case Nil => accumList
      case _ => {
        val min  = list.min
        val requiredList = list.filter(_ != min)
        selectSortHelper(requiredList, accumList ::: List.fill(list.length - requiredList.length)(min))
      }
    }
  }
  selectSortHelper(list)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment