Last active
August 29, 2015 14:27
-
-
Save InvisibleTech/897439527b6f5263cbc0 to your computer and use it in GitHub Desktop.
Selection Sort In Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
While refreshing how to determine orders of algorithms: O, Ω, atc. using an online tutorial, it covered selecton sort as an | |
example. So, I decided to implment it in Scala to be a generic version, sort of. | |
*/ | |
import Ordering.Implicits._ | |
def indexOfMinimum[T:Ordering](a: Array[T], start: Int) : Int = { | |
var minValue = a(start) | |
var mindex = start | |
for( i <- mindex+1 until a.length) { | |
if (a(i) < minValue) { | |
minValue = a(i) | |
mindex = i | |
} | |
} | |
return mindex | |
} | |
def swap[T](a: Array[T], to: Int, from: Int) : Unit = { | |
val temp = a(to) | |
a(to) = a(from) | |
a(from) = temp | |
} | |
def selectionSort[T:Ordering](a: Array[T]) : Unit = { | |
for (i <- 0 until a.length) { | |
val mindex = indexOfMinimum(a, i) | |
swap(a, i, mindex) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment