Skip to content

Instantly share code, notes, and snippets.

@jabley
Forked from Lytol/selection_sort.scala
Created November 4, 2009 16:14
Show Gist options
  • Save jabley/226158 to your computer and use it in GitHub Desktop.
Save jabley/226158 to your computer and use it in GitHub Desktop.
sort.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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment