Skip to content

Instantly share code, notes, and snippets.

@InvisibleTech
Created September 5, 2015 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InvisibleTech/39a23a10d8e3ddf01676 to your computer and use it in GitHub Desktop.
Save InvisibleTech/39a23a10d8e3ddf01676 to your computer and use it in GitHub Desktop.
Just wanted to play around with insertion sort to use for loops and learning more about Scala for loop conditions. Which is why I ended up implementing the insert with a while loop.
import Ordering.Implicits._
def insertionSort[T:Ordering](a: Array[T]) : Unit = {
for( i <- 1 until a.length) insert(a, i-1, a(i))
}
def insert[T:Ordering](a: Array[T], rightIndex: Int, x: T) {
var i = rightIndex
while (i >= 0 && a(i) > x) {
a(i+1) = a(i)
i -= 1
}
a(i + 1) = x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment